Anirban
Anirban

Reputation: 949

Get outer loop counter while iterating nested for-each loop in XSLT 1.0

I have an XML like the below:

<customer>
<fieldgroup>
<field index="1">field1</field>
<field index="2">field1</field>
</fieldgroup>
<fieldgroup>
<field index="1">field3</field>
<field index="2">field4</field>
</fieldgroup>
</customer>

The tag is repeaing and the tag which is inside it is also repeating. I am using XST 1.0 to transform this to target XML message where I will have to iterate both over and like:

<xsl for-each select="fieldgroup">
<xsl for-each select="field">
....
</xsl-for-each>
</xsl:for-each>

I will have to track which and item it is iterating over. In my code which is inside second for-each loop, I can get the loop couner of the loop but how will I get the loop counter of the parent for-each loop which is iteratin over ?

Upvotes: 0

Views: 410

Answers (1)

zx485
zx485

Reputation: 29042

Simply use a variable to store the position() of the <fieldgroup> elements:

<xsl:template match="customer">
  <xsl:for-each select="fieldgroup">
    <xsl:variable name="outerIndex" select="position()" />
    <xsl:for-each select="field">
        <xsl:value-of select="concat('#outer',$outerIndex,'#inner: ',@index,'#&#xa;')" />
    </xsl:for-each>
  </xsl:for-each>
</xsl:template>

Output is:

#outer1#inner: 1#
#outer1#inner: 2#
#outer2#inner: 1#
#outer2#inner: 2#

Upvotes: 1

Related Questions