xsl:for-each

The xsl:for-each element causes iteration over the nodes selected by a node-set expression. It can be used as an alternative to xsl:apply-templates where the child nodes of the current node are known in advance. There is a mandatory attribute, select, which defines the nodes over which the statement will iterate. The XSLT statements subordinate to the xsl:for-each element are applied to each source node selected by the node-set expression in turn.

The full syntax of expressions is outlined in XPath Expression Syntax.

The xsl:for-each element 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 expressions. The following are particularly useful:

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 also shows a template for a BOOKLIST element which processes all the child BOOK elements in order of their child AUTHOR elements.

<xsl:template match="BOOKLIST"> <h2> <xsl:for-each select="BOOK"> <xsl:sort select="AUTHOR"/> <p>AUTHOR: <xsl:value-of select="AUTHOR"/></p> <p>TITLE: <xsl:value-of select="TITLE"/></p> <hr/> </xsl:for-each> </h2> </xsl:template>

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. For details see saxon:threads.