XLST – For loop with counter

XLST Does support for each, but many times I wanted to see if I can implement something like traditional for loop i.e. using and increment counter. Well, below is my attempt at trying to implement xsl for loop which uses counters. This is implemented using named template which is called recursively. 

Sample Code:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<output>
<xsl:call-template name="forLoop">
<xsl:with-param name="count" select="0"/>
<xsl:with-param name="maxCount" select="5"/>
</xsl:call-template>
</output>
</xsl:template>
<xsl:template name="forLoop">
<xsl:param name="count"/>
<xsl:param name="maxCount"/>
<xsl:if test="$count &lt; $maxCount">
<count>
<xsl:value-of select="$count"/>
</count>
<xsl:call-template name="forLoop">
<xsl:with-param name="count" select="$count + 1"/>
<xsl:with-param name="maxCount" select="$maxCount"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>

Output:

<?xml version="1.0"?>
<output>
<count>0</count>
<count>1</count>
<count>2</count>
<count>3</count>
<count>4</count>
</output>

Leave Comment

Your email address will not be published. Required fields are marked *