XSLT <xsl:for-each> Element
- Previous Page XSLT <value-of>
- Next Page XSLT <sort>
The <xsl:for-each> element allows you to iterate in XSLT.
The <xsl:for-each> element
The <xsl:for-each> element can be used to select each XML element in a specified node set.
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
Note:select The value of the attribute is an XPath expression. This expression works like navigating a file system, where the forward slash can select subdirectories.
The above conversion results are similar to this:

Result Filtering
We can also filter the output from the XML file by adding a selection attribute predicate within the <xsl:for-each> element.
<xsl:for-each select="catalog/cd"[artist='Bob Dylan']">
Valid filter operators:
- = (equal)
- != (not equal)
- < (less than)
- > (greater than)
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd[artist='Bob Dylan"]"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
The above conversion results are similar to this:

- Previous Page XSLT <value-of>
- Next Page XSLT <sort>