2013-09-30 57 views
2

我是XSLT的新手。我想爲使用XSLT的現有子節點添加父節點。我的XML文件看起來像下面如何使用XSLT添加父節點

轉換之前轉換

<Library> 
     . 
     .//There is more nodes here 
     . 
     <CD> 
      <Title> adgasdg ag</Title> 
      . 
      .//There is more nodes here 
      . 
     </CD> 
     . 
     .//There is more nodes here 
     . 
     <CLASS1> 
     <CD> 
      <Title> adgasdg ag</Title> 
      . 
      .//There is more nodes here 
      . 
     </CD> 
     </CLASS1> 
     </Library> 

<Library> 
    <Catalog> 
    <CD> 
     <Title> adgasdg ag</Title> 
    </CD> 
    </Catalog> 
    <Class1> 
    <Catalog> 
     <CD> 
     <Title> adgasdg ag</Title> 
     </CD> 
    </Catalog> 
    </Class1> 
</Library> 

回答

3

要添加的元素Catalog你可以使用:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 

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

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

我通常會做什麼@markdark建議(重寫身份轉換),但如果你不這樣做需要修改以外的任何其他添加Catalog,你也可以做到這一點...

XSLT 2.0(也可以作爲1.0)

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

    <xsl:template match="/*"> 
     <xsl:copy> 
      <xsl:copy-of select="@*"/> 
      <Catalog> 
       <xsl:copy-of select="node()"/> 
      </Catalog> 
     </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet>