Using XSLT's `xsl:for-each` Element for Iterating and Generating Repeating Elements

Master the use of the XSLT `xsl:for-each` element for processing node sets and generating dynamic output. This tutorial explains its functionality, the `select` attribute, and provides practical examples demonstrating how to create repeating elements in your XSLT transformations based on your XML data.



Using the XSLT `xsl:for-each` Element

Understanding `xsl:for-each`

The XSLT `xsl:for-each` element is used to process a set of nodes from your XML input document. It's a fundamental element in XSLT for creating repetitive elements in the output. It iterates over a node-set, applying a template to each node in the set. This is a powerful way to generate dynamic output based on the structure of your XML data.

`xsl:for-each` Parameters

The key parameter for `xsl:for-each` is the `select` attribute. This attribute takes an XPath expression to determine the nodes that the `xsl:for-each` instruction should iterate over.

Example: Creating a Table of Employees

This example uses `xsl:for-each` to generate a table of employees from sample XML data. The XSLT stylesheet defines the table structure and iterates over each employee node, adding a row to the table for each employee.

1. Sample XML Data (`Employee.xml`)

Employee.xml

<Employees>
  <Employee id="1">
    <FirstName>Aryan</FirstName>
    <LastName>Gupta</LastName>
    <NickName>Raju</NickName>
    <Salary>30000</Salary>
  </Employee>
  <Employee id="2">
    <FirstName>Sara</FirstName>
    <LastName>Khan</LastName>
    <NickName>Zoya</NickName>
    <Salary>25000</Salary>
  </Employee>
  <!-- ... more employees ... -->
</Employees>

2. XSLT Stylesheet (`Employee.xsl`)

Employee.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <table border="1">
      <tr>
        <th>ID</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Nick Name</th>
        <th>Salary</th>
      </tr>
      <xsl:for-each select="/Employees/Employee">
        <tr>
          <td><xsl:value-of select="@id"/></td>
          <td><xsl:value-of select="FirstName"/></td>
          <td><xsl:value-of select="LastName"/></td>
          <td><xsl:value-of select="NickName"/></td>
          <td><xsl:value-of select="Salary"/></td>
        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>
</xsl:stylesheet>

Conclusion

The `xsl:for-each` instruction is a fundamental part of XSLT, providing a way to iterate over nodes and generate dynamic output. It simplifies the creation of repetitive elements in your transformed XML documents.