XSLT <xsl:for-each>
Element
The <xsl:for-each>
element allows you to perform loops in XSLT.
<xsl:for-each>
Element
The XSL <xsl:for-each>
element can be used to select each XML element in a specified node set:
Example
<?xml version="1.0" encoding="UTF-8"?>
<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: The value of the select attribute is an XPath expression. This XPath expression works similarly to navigating a file system, where the forward slash (/) selects subdirectories.
Filtering Output Results
By adding a conditional expression to the select attribute within the <xsl:for-each>
element, we can also filter the output results from the XML file.
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
Valid filtering operators:
= (equal to)
!= (not equal to)
< (less than)
(greater than)
Here is the adjusted XSL stylesheet:
Example
<?xml version="1.0" encoding="UTF-8"?>
<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>