Performing loops in XSLT

If you read this blog from time to time, you might have noticed that I am often talking about the XML/XSLT combo. Some people really don’t like declarative programming languages, because it is well, declarative. It works for me though.

(http://en.wikipedia.org/wiki/Declarative_programming). (Dimitre Novatchev actually proved [PDF 400kb] that XSLT can be used as a functional programming language)

One of the problems with XSLT is looping. To create a loop, you have to be able to update the same variable over and over again until you reach the desired value for that variable.
But XSLt doesn’t do that. if you declare a variable it will hold the same value untill the end. this bit really puzzles alot of people, but wait there is a solution.

You can get around almost any problem because most of the XSLT processors available, allow you to extend your XSLT stylesheet with JSCript, C# or whatever compiler is available on your system. But it is a bit messy.

If you start using this kind of combination of JavaScript and XSLT, your code gets unreadable very soon. So that is the reason why Oliver Becker created this nice loop extension. He uses nothing but XSLT that can be used as any other XSLT Extension. Have a look at the code below how it’s done:

<loop:for name="i" from="10" to="1" step="-1">
 <loop:for name="j" from="1" to="10">
  <xsl:value-of select="$i * $j" />
   <xsl:text>&#x9;</xsl:text>
  </loop:for>
 <xsl:text>&#xA;</xsl:text>
</loop:for>

He implemented for loop AND while loops.

<loop:while test="expression">
 <!-- optional some <xsl:variable> elements -->
  <loop:do>
   <!-- template body -->
    </loop:do>
    <loop:last>
   <!-- template body -->
  </loop:last>
 <!-- at least one <loop:update> element -->
</loop:while>

And a “function” to just update a variable:

<loop:update name="qname" select="expression" />

Have a look at the other XSLT stylesheets he is offering for download on his homepage:

  • Merging XML documents
  • Tracing execution of a stylehseet
  • Quine: The Self-Reproducing Stylesheet

Comments are closed.

Did you like it?
© 2003 - up to today