XSL Language doesn’t define any inbuilt construct for looping. Instead programmers should use the below example and adapt it according to your needs. Basic Concept => The template loop is recursively called var number of times.

<?xml version="1.0" encoding="US-ASCII" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="html" omit-xml-declaration="no" indent="yes" />

<xsl:template match="/">
  <xsl:call-template name="loop">
    <xsl:with-param name="var">5</xsl:with-param>
  </xsl:call-template>
</xsl:template>

<xsl:template name="loop">
  <xsl:param name="var"></xsl:param>
  <xsl:choose>
    <xsl:when test="$var &gt; 0">
      <xsl:text>I am in a loop</xsl:text>
      <xsl:text>&#xa;</xsl:text> <!-- newline -->
      <xsl:call-template name="loop">
        <xsl:with-param name="var">
        <xsl:number value="number($var)-1" />
        </xsl:with-param>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:text>I am out of the loop</xsl:text>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

</xsl:stylesheet> 

Run the above XSL File against any valid XML file. For ex.

<?xml version="1.0" encoding="US-ASCII"?>
<test>
</test>

The output will look like:

$ xsltproc xslloop.xsl test.xml
I am in a loop
I am in a loop
I am in a loop
I am in a loop
I am in a loop
I am out of the loop

Easy enough? 🙂

1 comment

Leave a Reply to joanna Cancel reply

You May Also Like