A Stylesheet That Emulates a for Loop
We stressed earlier that the xsl:for-each element is not a for loop; it’s merely an iterator across a group of nodes. However, if you simply must implement a for loop, there’s a way to do it. (Get ready to use recursion, though.)
Template Design
Our design here is to create a named template that will take some arguments, then act as a for loop processor. If you think about a traditional for loop, it has several properties:
One or more initialization statements. These statements are processed before the
forloop begins. Typically the initialization statements refer to an index variable that is used to determine whether the loop should continue.An increment statement. This statement specifies how the index variable should be updated after each pass through the loop.
A boolean expression. If the expression is
true, the loop continues; if it is everfalse, the loop exits.
Let’s take a sample from the world of Java and C++:
for (int i=0; i<length; i++)
In this scintillating example, the initialization statement is i=0, the index variable (the variable whose value determines whether we’re done or not) is i, the boolean expression we use to test whether the loop should continue is i<length, and the increment statement is i++.
For our purposes here, we’re going to make several simplifying assumptions. (Feel free, dear reader, to make the example as complicated as you wish.) Here are the shortcuts we’ll take:
Rather than use an initialization statement, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access