I'm reasonably new to xlst and am confused as to whether there is any way to store a value and change it later, for example incrementing a variable in a loop.
I'm a bit baffled by not being able to change the value of a after it's set doesn't make sense to me, making it more of a constant.
For example I want to do something like this:
<xsl:variable name="i" select="0" />
<xsl:for-each select="data/posts/entry">
<xsl:variable name="i" select="$i + 1" />
<!-- DO SOMETHING -->
</xsl:for-each>
If anyone can enlighten me on whether there is an alternative way to do this
Thanks
I ran into that myself two years ago. You need to do use recursion for this. I forget the exact syntax, but this site might help:
Tip: Loop with recursion in XSLT
The strategy works basically as follows: Replace
for
loop with a template "method". Have it recieve a parameteri
. Do the body of thefor
loop in the template method. Ifi > 0
call the template method again (recursion) withi - 1
as parameter.Pseudocode:
becomes:
Please note that using
position()
in axsl:for-each
(see other answers) can be simpler if all you want to do is have a variable increment. Use the kind of recursion explained here if you want a more complicated loop / condition.You can use the
position()
function:XSLT is a functional language and among other things this means that variables in XSLT are immutable and once they have been defined their value cannot be changed.
Here is how the same effect can be achieved in XSLT:
when this transformation is applied on the following XML document:
the result is: