Incrementing and checking the counter variable in XSLT

‘Variables’ in XSL are actually constants – you cannot change their value. This:

<xsl:value-of select="$counter + 1"/> 

will just output the value of $counter+1

To do loops you have to use recursion – e.g.:

<xsl:stylesheet 
  version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template name="loop">
    <xsl:param name="i"/>
    <xsl:param name="limit"/>
    <xsl:if test="$i &lt;= $limit">
      <div>
        <xsl:value-of select="$i"/>
      </div>
      <xsl:call-template name="loop">
        <xsl:with-param name="i" select="$i+1"/>
        <xsl:with-param name="limit" select="$limit"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

  <xsl:template match="https://stackoverflow.com/">
    <html>
      <body>
        <xsl:call-template name="loop">
          <xsl:with-param name="i" select="0"/>
          <xsl:with-param name="limit" select="10"/>
        </xsl:call-template>
      </body>
    </html>
  </xsl:template>

</xsl:stylesheet>

altough it is better to try to avoid loops – in most cases the XSL can be written to avoid it, but I don’t understand enough of what are you trying to achieve to give you the complete solution.

Leave a Comment