2017-04-14 82 views
0

我正在为以下输入和输出XML寻找XSLT(1.0)代码。XSLT - 复制所有节点并在复制的节点中添加额外的节点

在输出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

你给我们提出了要求,但如果您有任何问题,你还没有告诉我们你已经尝试什么,或者。没有实际的问题。它似乎更像是一个[“你是否需要编码吗?”](https://english.stackexchange.com/q/13231)请求。 –

+0

虽然在da codez上发生冲突,但也许你可以解释为什么第一个NewNode有一个2,第二个NewNode有一个1.另外,为什么NewNode1获取它的值。 – Bluewood66

+0

@DanielHaley - 感谢您的评论。其实我不是XSLT的专家。由于它对我来说似乎有点复杂,我张贴了我的要求。 – Nilay

回答

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>