How-to break a for-each loop in XSLT?
Why would you want to? Perhaps for-each is not the construct you want in this case?
XSLT is written in a very functional style, and in this style there is no equivalent of a break
statement. What you can do is something like this:
<xsl:for-each select="...nodes...">
<xsl:if test="...some condition...">
...body of loop...
</xsl:if>
</xsl:for-each>
That way the for-each
will still iterate through all the nodes, but the body of the loop will only be executed if the condition is true.
XSLT isn't a procedural language; don't think of for-each as being a "loop" in the way you have a loop in Java. For-each is a way to apply a template to each of a bunch of items. It doesn't necessarily happen in a particular order, so you can't think of it as "apply this template to each of a bunch of items until such-and-such happens, then stop".
That said, you can use the select attribute to filter the results, so it becomes more like "apply a template to each of a bunch of items, but only if such-and-such is true of them".
If what you really want is "apply a template to each of a bunch of items, where such-and-such is true of them, but only to the first one this is true of", you can combine the select attribute with the position() function.
A "break" from the body of an <xsl:for-each>
XSLT instruction cannot be specified using a syntactic construct, however it can be simulated.
This code snippet at topxml.com describes the technique in detail:
In case you need a ""break"" from an xsl:for-each loop
Essentially two techniques are discussed:
Performing something inside the body of
<xsl:for-each>
only if a specific condition is satisfied.Specifying the processing not using
<xsl:for-each>
but with recursion
The second method has the benefit of being able to perform the exit immediately, contrasted with the first method having to still perform many "empty cycles" even after the exit-condition has been satisfied.