current index value in xsl

1.9k views Asked by At

Hey I have a scenario where I have a xml structure like

<deftms>
<tn>abc</tn>
<td>xyz</td>
<tn>abc1</tn>
<td>xyz1</td>
<tn>abc2</tn>
<td>xyz2</td>
</deftms>

want to convert it as :

<deftms>
     <newtms>
        <tn>abc</tn>
        <td>xyz</td>
     </newtms>
     <newtms>
        <tn>abc1</tn>
        <td>xyz1</td>
     </newtms>
     <newtms>
       <tn>abc2</tn>
        <td>xyz2</td>
     </newtms>
</deftms>

am using following transform xsl code to achieve the output

<xsl:template name = "deftms">  
    <deftms>
      <xsl:for-each select="//deftms/tn">
<xsl:variable name="tn"><xsl:value-of select="current()" /></xsl:variable>
<xsl:variable name="td"><xsl:value-of select="(current())" /></xsl:variable>
<newtms>
    <tn><xsl:copy-of select="$tn" /></tn>
        <td><xsl:copy-of select="$td" /></td>
 </newtms>
      </xsl:for-each>
    </deftms>
</xsl:template>

Anyone any idea ?

3

There are 3 answers

0
Michael Kay On

Try:

<xsl:template name = "deftms">  
    <deftms>
      <xsl:for-each select="tn">
       <newtms>
        <xsl:copy-of select=". | following-sibing::td[1]" />
       </newtms>
      </xsl:for-each>
    </deftms>
</xsl:template>
0
Ian Roberts On

Within the for-each the position() function will give you what you need. It returns the (one-based) index of the node currently being processed, within the list of nodes that the for-each selected - informally the "iteration number" (though for-each need not necessarily be implemented as a loop within the processor).

<xsl:template name = "deftms">  
  <deftms>
    <xsl:for-each select="//deftms/tn">
      <xsl:variable name="pos" select="position()" />
      <xsl:variable name="td" select="../td[$pos]" />
      <newtms>
        <tn><xsl:copy-of select="." /></tn>
        <td><xsl:copy-of select="$td" /></td>
      </newtms>
    </xsl:for-each>
  </deftms>
</xsl:template>
0
sreevathsa a On

Try below one

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="deftms" name ="ParentCopy">
<xsl:copy>
    <xsl:param name="LoopCountA">1</xsl:param>
    <xsl:variable name = "CountDate" >

        <xsl:value-of select = "count(tn)"/>

    </xsl:variable>
    <xsl:choose>
        <xsl:when test = " $LoopCountA  &lt;= $CountDate " >

                <newtms>
                    <xsl:copy-of select="tn[position()= $LoopCountA]"/>
                    <xsl:copy-of select ="td[position()= $LoopCountA]"/>
                </newtms>

            <xsl:call-template name="ParentCopy">

                <xsl:with-param name="LoopCountA">
                    <xsl:value-of select="$LoopCountA + 1"/>
                </xsl:with-param>

            </xsl:call-template>
        </xsl:when>
    </xsl:choose>
        </xsl:copy>


</xsl:template>

</xsl:stylesheet>