2012-12-18 33 views
0

我有一个XML文档,我想要警察<,但我不知道如何翻译一个特殊属性。复制XML并在gernal中替换属性工作正常,但我不知道如何在XSL中定义一个短语列表,然后将它们翻译成另一个短语。XSL要替换的单词列表,最容易定义

该定义应该易于阅读。 translate()是否吞下某种列表表示?一个小例子使用translate会很好(不关心XML复制的东西)。

回答

1

XPath和XSLT 1.0的translate函数仅用于将一个Unicode字符替换为另一个Unicode字符;您可以提供一个输入和替换字符列表,然后第一个列表中的每个字符将被替换为第二个列表中相同位置的字符。但要取代完整的作品或短语,您需要其他工具。

假设您可以(使用XSLT 2.0)简单地执行例如,您尚未说明或描述是否要替换完整的属性值。

<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="2.0"> 

<xsl:key name="phrase" match="phrase" use="@input"/> 

<xsl:param name="phrases"> 
    <phrases> 
    <phrase input="IANAL" output="I am not a lawyer"/> 
    <phrase input="WYSIWYG" output="What you see is what you get"/> 
    </phrases> 
</xsl:param> 

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* , node()"/> 
    </xsl:copy> 
</xsl:template> 


<xsl:template match="foo/@bar"> 
    <xsl:attribute name="baz" select="key('phrase', ., $phrases)/@output"/> 
</xsl:template> 

</xsl:stylesheet> 

这样式表转换例如

<root> 
    <foo bar="IANAL"/> 
    <foo bar="WYSIWYG"/> 
</root> 

<root> 
    <foo baz="I am not a lawyer"/> 
    <foo baz="What you see is what you get"/> 
</root> 

如果你想要做的子串的几种替代物中的一个值或字符串,则需要更多的努力,但与replace在XSLT/XPath 2.0中也可能发挥作用。

[编辑]下面是使用的项目的列表和一个递归函数替换短语的例子:

<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    xmlns:mf="http://example.com/mf" 
    exclude-result-prefixes="xs mf" 
    version="2.0"> 

<xsl:key name="phrase" match="phrase" use="@input"/> 

<xsl:function name="mf:replace-phrases" as="xs:string"> 
    <xsl:param name="phrases" as="element(phrase)*"/> 
    <xsl:param name="text" as="xs:string"/> 
    <xsl:choose> 
    <xsl:when test="not($phrases)"> 
     <xsl:sequence select="$text"/> 
    </xsl:when> 
    <xsl:otherwise> 
     <xsl:sequence select="mf:replace-phrases($phrases[position() gt 1], replace($text, $phrases[1]/@input, $phrases[1]/@output))"/> 
    </xsl:otherwise> 
    </xsl:choose> 
</xsl:function> 

<xsl:param name="phrases"> 
    <phrases> 
    <phrase input="IANAL" output="I am not a lawyer"/> 
    <phrase input="WYSIWYG" output="What you see is what you get"/> 
    </phrases> 
</xsl:param> 

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* , node()"/> 
    </xsl:copy> 
</xsl:template> 


<xsl:template match="foo/@bar"> 
    <xsl:attribute name="baz" select="mf:replace-phrases($phrases/phrases/phrase, .)"/> 
</xsl:template> 

</xsl:stylesheet> 

即变换示例

<root> 
    <foo bar="He said: 'IANAL'. I responded: 'WYSIWYG', and he smiled."/> 
</root> 

<root> 
    <foo baz="He said: 'I am not a lawyer'. I responded: 'What you see is what you get', and he smiled."/> 
</root> 
+0

谢谢,我使用v2,但创建的属性总是空的(在每个元素中,即使我只定义了一个测试短语)。测试是否适合你? –

+0

sry,我的错。我在事物的周围包裹了一个“选择”子句,以阻止不相关的值被空字符串替换 –