1. xsl for-each
2. xsl for each usage.
3. When to use for-each


xsl for-each

Michael Kay

It helps to think about these problems if you understand the processing model. <xsl:for-each> isn't a loop: it's a function mapping. It says that in the output you want one Y for every X that appears in the input. Since it's not a loop, jumping out of it doesn't make sense. What you need is a different function.

There are a number of places in the XSLT spec where the semantics are explained using a sequential processing model, however, the language has been carefully designed so that implementations do not have to follow this sequential mechanism: it is there purely as a way of explaining the effect of the language. Not an ideal situation, but it doesn't alter the fact that the underlying semantics are functional rather than sequential.


xsl for each usage.

Mike Kay

<xsl:for-each select="//NAD2[index]">

You don't need to specify a "subscript" in for-each: the select-expression should evaluate to the set of nodes you want to process, not to an individual node in the set. While you are processing an individual node, you can determine its position in the set using the position() function.


When to use for-each

Mike Kay

I use a guideline, which is to use xsl:for-each when you use the position() or last() function in the 'template' (the content of the xsl:for-each or xsl:template).

The reason for this is that the result of the position()/last() functions for a particular node are completely dependant on the nodes that are selected for processing. I think keeping the location path that selects the nodes and the use of the position()/last() functions close together (as you do with an xsl:for-each) makes the stylesheet easier to understand and maintain than when the location path and the function call are in completely different parts of the stylesheet.