XSLT - 复制所有节点并在复制的节点中添加额外节点

时间:2017-04-14 14:41:11

标签: xslt xslt-1.0

我正在寻找以下输入和输出XML的XSLT(1.0)代码。

在输出XML中,C6元素下可以有任何子节点。在下面的XML中,我已经放置了CN元素,但它可以是任何名称。

输入XML -

    <?xml version = "1.0" encoding = "UTF-8"?>
    <root>
        <input>
            <c2>
                <c3>
                    <c4>c4</c4>
                </c3>
            </c2>
        </input>
        <output>
            <c5>
                <c6>
                    <CN>
                        <T1></T1>
                        <T2></T2>
                    </CN>
                </c6>
                <c6>
                    <CN>
                        <T1></T1>
                        <T2></T2>
                    </CN>
                </c6>
            </c5>
        </output>
    </root>

所需的输出XML -

    <root>
    <output>
            <c5>
                <c6>
                <!-- It could have any child node. Putting an example with CN child node name.-->
                    <CN>
                        <T1></T1>
                        <T2></T2>
                        <c3>
                            <c4>c4</c4>
                            <NewNode>current number of CN node which will be 1</NewNode>
                            <NewNode1>total number of C6 nodes which will be 2.</NewNode1>
                        </c3>
                    </CN>
                </c6>
                <c6>
                    <CN>
                        <T1></T1>
                        <T2></T2>
                        <c3>
                            <c4>c4</c4>
                            <NewNode>current number of CN node which will be 2</NewNode>
                            <NewNode1>total number of C6 nodes which will be 2.</NewNode1>
                        </c3>
                    </CN>
                </c6>
            </c5>
        </output>
    </root>

提前谢谢。

1 个答案:

答案 0 :(得分:0)

使用以下样式表:

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

  <xsl:template match="c6/*">
    <xsl:copy>
        <xsl:variable name="v1" select="count(../preceding-sibling::*)+1"/>
        <xsl:variable name="v2" select="count(../../*)"/>
        <xsl:apply-templates/>
        <xsl:apply-templates select="../../../../input/c2/c3">
          <xsl:with-param name="v1" select="$v1"/>
          <xsl:with-param name="v2" select="$v2"/>
        </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="c3">
    <xsl:param name="v1"/>
    <xsl:param name="v2"/>
    <xsl:copy>
      <xsl:apply-templates/>
      <NewNode><xsl:value-of select="$v1"/></NewNode>
      <NewNode1><xsl:value-of select="$v2"/></NewNode1>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="input"/>

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