A Sample Loop in XSL, Alternative for While, For Loops

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:template name="loop">
  <xsl:param name="var"></xsl:param>
    <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:text>I am out of the loop</xsl:text>


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

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

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? 🙂

About Pratik Sinha

Linux Nerd, Socialist, Atheist, Adventuristic, Nature Lover, Geeky.

1 comment

Leave a Reply