Name

<xsl:for-each>

XSLT’s iteration operator. This element has a select attribute that selects some nodes from the current context. The contents of the <xsl:for-each> element are then evaluated using each of the selected nodes. ([2.0] In XSLT 2.0, the select attribute selects items, which can include atomic values as well as nodes.)

Category

Instruction.

Required Attribute

select

Contains an XPath expression that selects nodes from the current context.

Optional Attributes

None.

Content

<xsl:for-each> contains a template that is evaluated against each of the selected nodes. The <xsl:for-each> element can contain one or more <xsl:sort> elements to order the selected nodes before they are processed. All <xsl:sort> elements must appear first, before the template begins.

Appears in

<xsl:for-each> appears inside a template.

Defined in

[1.0] XSLT section 8, “Repetition.”

[2.0] XSLT section 7, “Repetition.”

Example

We’ll demonstrate the <xsl:for-each> element with the following stylesheet:

<?xml version="1.0"?>
<!-- for-each.xsl --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:text>&#xA;Here is a moderately long list: </xsl:text> <xsl:variable name="listitems" select="list/listitem"/> <xsl:call-template name="processListitems"> <xsl:with-param name="items" select="$listitems"/> </xsl:call-template> </xsl:template> <xsl:template name="processListitems"> <xsl:param name="items"/> <xsl:for-each select="$items"> <xsl:value-of ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.