Skip to main content

XSLT <xsl:for-each> Element

The <xsl:for-each> element applies a template repeatedly for each node.

<xsl:for-each> Element

The <xsl:for-each> element can be used to select each XML element of a specified set of nodes and apply a template to them.


The syntax of <xsl:> is as follows:



The table describes the meaning of the attributes of <xsl:>:

selectXPath Expression to be evaluated in current context to determine the set of nodes to be iterated.

Filtering the Output

The output from the XML file can be filtered by adding a criterion to the select attribute in the <xsl:for-each> element.

Allowed filter operators are:

  • = equal
  • != not equal
  • &lt; less than
  • &gt; greater than

For example:

<xsl:for-each select="bookstore/book[author='Tom Nolan']">


Let's see an example:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>

<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<book category="web">
<title lang="en">XQuery Tips</title>
<author>Tom Nolan</author>
<book category="web">
<title lang="en">Learn XML</title>
<author>Tutorial Reference</author>
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="">

<xsl:template match="/">
<h2>The Bookstore</h2>
<table border="1">
<tr bgcolor="#6565d5">
<xsl:for-each select="bookstore/book">
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="year"/></td>
<td><xsl:value-of select="price"/></td>


The select attribute contains an XPath expression.

An XPath expression works like navigating a file system and a forward slash (/) selects subdirectories.