XSLT for each

XSLT <xsl:for-each> Element

If we want to do looping in XSL, the <xsl:for-each> element is a must.

The <xsl:for-each> Element:

We can select each XML element of a specified node-set using the XSL <xsl:for-each> element.

Example:

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>100.00</price>
  </book>
 
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <year>2020</year>
    <price>300.00</price>
  </book>
 
</bookstore>

XSLT Code:

<?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>List of Books</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th style="text-align:left">Title</th>
      <th style="text-align:left">Price</th>
    </tr>
    <xsl:for-each select="bookstore/book">
    <tr>
      <td><xsl:value-of select="title"/></td>
      <td><xsl:value-of select="price"/></td>
    </tr>
    </xsl:for-each>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Output:

Filtering the Output:

In the <xsl:for-each> element, we can add a criterion to the select attribute to filter the output from the XML file. An XPath expression is present in the select attribute, that works like navigating a file system, where a forward slash (/) selects subdirectories.

Example:

<xsl:for-each select="bookstore/book[price='100.00']">

Legal filter operators:

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

Example: Adjusted XSL Stylesheet:

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>100.00</price>
  </book>
 
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <year>2020</year>
    <price>300.00</price>
  </book>
 
</bookstore>

XSLT Code:

<?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>List of Books</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th style="text-align:left">Title</th>
      <th style="text-align:left">Price</th>
    </tr>
    <xsl:for-each select="bookstore/book[price='100.00']">
    <tr>
      <td><xsl:value-of select="title"/></td>
      <td><xsl:value-of select="price"/></td>
    </tr>
    </xsl:for-each>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Output:

Please Share