2012-12-18 34 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,我的錯。我在事物的周圍包裹了一個「選擇」子句,以阻止不相關的值被空字符串替換 –