XSLT » Elements » xsl:for-each

Syntax:
<xsl:for-each
  select="expression"
/>
</xsl:for-each>

The xsl:for-each element loops through each node in a node set in itsr order of occurrence and applies the same template to each node. A node set is simply the collection of all of the same XML tags (nodes) in an XML file. This process is also referred to as iterating over a set of nodes. The template is contained inside the xsl:for-each element between the opening and closing element. The syntax is:

<xsl:for-each>
    code ...
</xsl:for-each>

 
In a formal definition, the template is said to be instantiated once to each node in the node set.
 
The default is to iterate through the nodes in the order in which they occur. This is referred to as document order. However, you may prefer to rearrange the order by using the xsl:sort element. This element defines the sort key upon which the sort (reorder) will be based.
 
This element is not self-closing. The separate closing element is mandatory.

Examples

Code:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="devguru_staff/programmer">
<div>
NAME: <xsl:value-of select="name" />
<br />
DOB: <xsl:value-of select="dob" />
<br />
AGE: <xsl:value-of select="age" />
<br />
ADDRESS: <xsl:value-of select="address" />
<br />
PHONE: <xsl:value-of select="phone" />
<hr />
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output:
NAME: Bugs Bunny
DOB: 03/21/1970
AGE: 31
ADDRESS: 4895 Wabbit Hole Road
PHONE: 865-111-1111
NAME: Daisy Duck
DOB: 08/09/1949
AGE: 51
ADDRESS: 748 Golden Pond
PHONE: 865-222-2222
NAME: Minnie Mouse
DOB: 04/13/1977
AGE: 24
ADDRESS: 4064 Cheese Factory Blvd
PHONE: 865-333-3333
NAME: Pluto
DOB: 07/04/1979
AGE: 21
ADDRESS: 414 Dog Lane
PHONE:
NAME: Porky Pig
DOB: 11/30/1956
AGE: 44
ADDRESS: 555 Mud Pit Pike
PHONE: 865-444-4444
NAME: Road Runner
DOB: 01/19/1953
AGE: 48
ADDRESS: 135 Desert View Street
PHONE: 865-555-5555
Explanation:

This is the code for xslt_example_foreach.xsl.
 
We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_foreach.xsl"?>

Language(s): XSLT

See Also: