如何使用XSLT添加父节点

时间:2013-09-30 19:41:44

标签: xslt xslt-2.0

我是XSLT的新手。我想使用XSLT为现有子节点添加父节点。我的XML文件如下所示

转换前

  <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>

2 个答案:

答案 0 :(得分:4)

要添加元素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>

答案 1 :(得分:3)

我通常会完全按照@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>