2014-12-02 49 views
0

讓我們說我有這個輸入文件更換一個節點的價值

<root> 

    <keyword> 
     <name>foo</name> 
     <value>bar</value> 
    </keyword> 
    <keyword> 
     <name>123</name> 
     <value>456</value> 
    </keyword> 

</root> 

,我想這樣的輸出:

<root> 

    <keyword> 
     <name>foobar</name> 
     <value>bar</value> 
    </keyword> 
     <keyword> 
     <name>123</name> 
     <value>456</value> 
    </keyword> 

</root> 

現在,我有這樣的工作轉變,但我想知道如何使其更加優雅。

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

    <!-- copy all nodes and attributes --> 
    <xsl:template match="@*|node()" name = "identity"> 
     <xsl:copy > 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match = "/root/keyword/name[text() = 'foo']"> 
     <name>foobar</name> 
    </xsl:template> 

</xsl:stylesheet> 

匹配所需的節點後,我再次重複設置它,而不是簡單地將其替換。我可以更優雅地做到這一點嗎?我的要求可能聽起來有些荒謬,但我想更深入地瞭解xslt並更好地理解。

非常感謝!

+0

我會將'match =「/ root/keyword/name [text()='foo']」'縮短爲'match =「/ root/keyword/name [。='foo']」'。您需要添加更多詳細信息,例如前綴'calypso'的名稱空間聲明,以便我們可以更多地改進代碼。 – 2014-12-02 18:06:42

+0

我已經移除了名稱空間,這是在轉換中的一個位置聲明的(我錯誤,忘記刪除)。除此之外,輸入和轉換都是我的文件的逐字副本,沒有聲明額外的名稱空間。謝謝! – 2014-12-02 18:38:09

回答

2

假設XSLT 2.0,我會(在http://xsltransform.net/3NzcBsW在線)做這樣的:

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

    <xsl:param name="old" select="'foo'"/> 
    <xsl:param name="new" select="'foobar'"/> 

    <!-- copy all nodes and attributes --> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="/root/keyword/name[. = $old]"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*"/> 
      <xsl:value-of select="$new"/> 
     </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 

似乎與參數更加靈活。除此之外,我沒有辦法縮短它,身份轉換模板是轉換的核心,並且輸入XML樣本特定的一個模板確保我們正在尋找的name元素獲取新內容。

+0

您還可以將''更改爲''來處理'name'中的可能屬性。 – 2014-12-02 19:30:27

+0

我同意在一般解決方案中也應該包含屬性,但在這種情況下,我更喜歡使用''來集成允許覆蓋身份的一般方法轉換模板以在需要時轉換它們。 – 2014-12-03 10:11:09

+0

這也是我所喜歡的,但題目爲「替換一個節點的值」的問題,我認爲副本是合適的。 – 2014-12-03 15:05:47