XSLT - What is <xsl:for-each>?
What is <xsl:for-each>
?
In XSLT (Extensible Stylesheet Language Transformations), the <xsl:for-each>
element is used to loop through a set of nodes selected by an XPath expression.
Think of it like a for
loop in other programming languages, but here it’s looping over XML nodes.
Syntax
<xsl:for-each select="XPath_expression">
<!-- Instructions to execute for each node -->
</xsl:for-each>
-
select
→ defines which nodes you’re looping through. -
Inside the loop, you can output values, apply templates, or add formatting.
Example
Suppose you have an XML file:
<books>
<book>
<title>XML Fundamentals</title>
<author>Alice Johnson</author>
</book>
<book>
<title>XSLT in Action</title>
<author>Bob Smith</author>
</book>
<book>
<title>Advanced XPath</title>
<author>Carol White</author>
</book>
</books>
XSLT using <xsl:for-each>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<body>
<h2>Book List</h2>
<ul>
<xsl:for-each select="books/book">
<li>
<xsl:value-of select="title"/> -
<xsl:value-of select="author"/>
</li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output (HTML result)
<html>
<body>
<h2>Book List</h2>
<ul>
<li>XML Fundamentals - Alice Johnson</li>
<li>XSLT in Action - Bob Smith</li>
<li>Advanced XPath - Carol White</li>
</ul>
</body>
</html>
Key Points
-
<xsl:for-each>
iterates over all nodes matched by the XPath. -
Inside the loop, you can access each node’s child elements using
xsl:value-of
. -
You can also sort nodes using
<xsl:sort>
inside<xsl:for-each>
.