XSL Tips - Recursion

William Pohlhaus' Web Site

Home > XSL Tips > Recursion


Side Links
Home
Resume
Jennifer (wedding picutes)
Seda (baby pictures)
Java
Presentation
XSL Tips
My Other Homepage (Dust Boy)
Summer 2003 Independent Studies
 
Recursion
  This examples shows how you can call a template recursitively in xsl. Note that is follows the base rules for recursion:
1. It calls itself
2. At least one parameter changes
3. As a way to end
This is useful when you need to use recursion of course, but more importantly to do a loop not base on xml nodes because there is no independent of node loop functions in xsl. Remember that xsl:for-each will loop through each matching node.
XML
<?xml version="1.0" encoding="US-ASCII" ?>

<test>m</test>

XSL
<?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="test">
    <xsl:call-template name="loop">
      <xsl:with-param name="var">3</xsl:with-param>
    </xsl:call-template>

  </xsl:template>

  <xsl:template name="loop">
    <xsl:choose>
      <xsl:when test="$var &gt; 0">
        test
        <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>
        weird
      </xsl:otherwise>
    </xsl:choose>

  </xsl:template>

</xsl:stylesheet>
Result
test test test weird