如何使用 XSLT 添加父节点



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

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

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

最新更新