xsl:for-each
Causes iteration over a specified sequence of items.
Category: instruction
Content: (
xsl:sort*
, sequence-constructor
)
Permitted parent elements:
any XSLT element whose content model is
sequence-constructor; any literal result element
Attributes
|
| Defines the sequence of items over which
the statement will iterate. The XSLT statements subordinate to the
|
|
| New in XSLT 4.0. The value is an attribute value template. If present, a text node is formed from the effective value of the attribute, and this text node is inserted into the result sequence after processing every item in the (sorted) input sequence other than the last. |
|
| The items
selected by the |
Saxon availability
Available in XSLT 1.0 and later versions. Available in all Saxon editions. Available for all platforms.
Notes on the Saxon implementation
Saxon-EE offers an extension to the xsl:for-each instruction; the saxon:threads attribute allows the items in the input sequence to be
processed in parallel. This is most likely to be effective when (a) the
processing of each item is expensive, and (b) the output produced by processing
each item is small. Allocating multiple threads when each item generates a new
result document is pointless, because xsl:result-document already
runs in a separate thread.
For xsl:for-each to be streamable, the W3C rules require that the
select expression must be "striding", which essentially means
that it may use the child axis but not the descendant axis (to ensure that
selected nodes do not overlap each other). In many cases the restriction can be
circumvented by using the outermost function, for example the
expression outermost(//title) is striding even though it uses the
descendant axis.
The separator attribute is available from Saxon 13 in
XSLT 4.0; it is available in Saxon 11 and 12 provided that syntax
extensions are enabled.
Details
The xsl:for-each element can be used as an alternative to xsl:apply-templates
where the child nodes of the current node are known in advance.
It may have one or more xsl:sort child elements to define the order of sorting. The sort keys are specified in major-to-minor order. The expression used for sorting can be any string expression. The following are particularly useful:
-
element-name, e.g.
TITLE: sorts on the value of a child element -
attribute-name, e.g.
@CODE: sorts on the value of an attribute -
".": sorts on the character content of the element -
"qname(.)": sorts on the name of the element
Examples
Example 1
<xsl:template match="BOOKLIST"> <TABLE> <xsl:for-each select="BOOK"> <TR> <TD><xsl:value-of select="TITLE"/></TD> <TD><xsl:value-of select="AUTHOR"/></TD> <TD><xsl:value-of select="ISBN"/></TD> </TR> </xsl:for-each> </TABLE> </xsl:template>Example 2
Sorting with xsl:for-each. This example shows a template for a
<BOOKLIST> element which processes all the child
<BOOK> elements in order of their child
<AUTHOR> elements.