2015-06-29 34 views
0

我有這樣的XML,XSLT - 模板並不適用於某些節點

<?xml version="1.0" encoding="UTF-8"?> 
<catalog> 
    <cd> 
     <title>Empire Burlesque</title> 
     <artist>Bob Dylan</artist> 
     <country>USA</country> 
     <company>Columbia</company> 
     <price>10.90</price> 
     <year>1985</year> 
    </cd> 
    <cd> 
     <title>Hide your heart</title> 
     <artist>Bonnie Tyler</artist> 
     <country>UK</country> 
     <company>CBS Records</company> 
     <price>9.90</price> 
     <year>1988</year> 
    </cd> 
    <cd> 
     <title>Unchain my heart</title> 
     <artist>Joe Cocker</artist> 
     <country>USA</country> 
     <company>EMI</company> 
     <price>8.20</price> 
     <year>1987</year> 
    </cd> 
</catalog> 

我需要做的是從原始的XML刪除<year>節點,改變<artist>節點<name>和添加新節點(<time><version>)在最後的<cd>節點處。

我已經寫了下面的XSLT代碼,

<xsl:variable name="time" as="xs:dateTime" select="current-dateTime()"/> 
<xsl:variable name="version" as="xs:double" select="1.0"/> 

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

    <xsl:template match="catalog/cd/artist"> 
     <name><xsl:apply-templates/></name> 
    </xsl:template> 

    <xsl:template match="catalog/cd/year"/> 

    <xsl:template match="catalog/cd[last()]"> 
     <xsl:copy-of select="."/> 
     <time><xsl:value-of select="$time"/></time> 
     <version><xsl:value-of select="$version"/></version> 
    </xsl:template> 

輸出是如下,

<?xml version="1.0" encoding="UTF-8"?><catalog> 
    <cd> 
     <title>Empire Burlesque</title> 
     <name>Bob Dylan</name> 
     <country>USA</country> 
     <company>Columbia</company> 
     <price>10.90</price> 

    </cd> 
    <cd> 
     <title>Hide your heart</title> 
     <name>Bonnie Tyler</name> 
     <country>UK</country> 
     <company>CBS Records</company> 
     <price>9.90</price> 

    </cd> 
    <cd> 
     <title>Unchain my heart</title> 
     <artist>Joe Cocker</artist> 
     <country>USA</country> 
     <company>EMI</company> 
     <price>8.20</price> 
     <year>1987</year> 
    </cd> 
    <time>2015-06-29T13:41:49.885+05:30</time> 
    <version>1</version> 
</catalog> 

正如你看到的,代碼工作正常,但只有最後一個節點似乎沒有應用模板(在最後節點<artist>節點未發生變化<year>節點出現)。

我該如何解決這個問題。

回答

1

變化

<xsl:template match="catalog/cd[last()]"> 
    <xsl:copy-of select="."/> 
    <time><xsl:value-of select="$time"/></time> 
    <version><xsl:value-of select="$version"/></version> 
</xsl:template> 

<xsl:template match="catalog/cd[last()]"> 
    <xsl:copy> 
     <xsl:apply-templates> 
     <time><xsl:value-of select="$time"/></time> 
     <version><xsl:value-of select="$version"/></version> 
    </xsl:copy> 
</xsl:template> 
+0

它的工作原理。謝謝 – sanjay

1

在你的最後一個模板,替換:

<xsl:copy-of select="."/> 

有:

<xsl:copy> 
    <xsl:apply-templates/> 
</xsl:copy> 
+0

它的工作原理。謝謝 – sanjay