tags:

views:

1592

answers:

2
+3  Q: 

index in loop XSL

I have two nested loop in XSL like this, at this moment I use position() but it's not what I need.

<xsl:for-each select="abc">
  <xsl:for-each select="def">
   I wanna my variable in here increasing fluently 1,2,3,4,5.....n
not like 1,2,3,1,2,3
  </xsl:for-each>
</xsl:for-each>

Can you give me some idea for this stub. Thank you very much!

+4  A: 
<xsl:for-each select="abc">
    <xsl:variable name="i" select="position()"/>
    <xsl:for-each select="def">
        <xsl:value-of select="$i" />
    </xsl:for-each>
</xsl:for-each>
Chris Doggett
this will not produce a 1,2,3,4,... sequence unless there's only one nested "def" tag under the "abc" tag.
pythonquick
Thank you Chris Doggett but my problem is that when I use position() in the second loop inside it continues from rezo not by the last index in the first loop. So I could not use your suggest! But your suggest may be useful for me recently, thank again Chris!
gacon
+2  A: 

With XSL, the problem is you cannot change a variable (it's more like a constant that you're setting). So incrementing a counter variable does not work.

A clumsy workaround to get a sequential count (1,2,3,4,...) would be to call position() to get the "abc" tag iteration, and another call to position() to get the nested "def" tag iteration. You would then need to multiply the "abc" iteration with the number of "def" tags it contains. That's why this is a "clumsy" workaround.

Assuming you have two nested "def" tags, the XSL would look as follows:

<xsl:for-each select="abc">
    <xsl:variable name="level1Count" select="position() - 1"/>
    <xsl:for-each select="def">
        <xsl:variable name="level2Count" select="$level1Count * 2 + position()"/>
        <xsl:value-of select="$level2Count" />
    </xsl:for-each>
</xsl:for-each>
pythonquick
Thank you very much pythonquick, you code work fine for me! It took me waste alot of time. Thank you!
gacon
Note that this will work only if every `abc` has equal number of def children. Also, this only works with a hard-coded `def` count.
jelovirt