Re: [xsl] build a counter variable

Subject: Re: [xsl] build a counter variable
From: Michael Kay <mike@xxxxxxxxxxxx>
Date: Fri, 06 Jan 2012 09:48:06 +0000
On 06/01/2012 08:54, henry human wrote:
Hi
I have an XSLT structure as bellow. I tried to build a counter with the position () function .But it does not work because the position () function ever begins with 1 in a loop. (In node1, node2, node3 the position begins with 1 (position= 1))



<xsl:for-each select="node1/m"> <m><xsl:value-of select="position()"/> </m> <== position should be 1 ....... <xsl:for-each select="node1/node2/a"> <a>....</a> <== position = 2 <a>....</a> <== position = 3 <a>.....</a> <== position = 4 </xsl:for-each>

<xsl:for-each select="node1/node3/f1">

  <f1><xsl:value-of select="position()"/></f1>                                    <== position = 5
</xsl:for-each>

</xsl:for-each>


If you are using XSLT 2.0, you could do

<xsl:apply-templates select="node1/m, node1/node2/a, node1/node3/f1"/>

and then do the processing of different node kinds in template rules

<xsl:template match="node1/m">
etc

Within those templates position() will have the right value.

This depends on the fact that XSLT 2.0 allows node sequences rather than merely node sets. You may be able to achieve the same effect in XSLT 1.0 if (a) the nodes are processed in document order, or (b) you can define the order of processing using a sort key.

Michael Kay
Saxonica

Current Thread