XSLT - <xsl:apply-templates> (with select) to <xsl:for-each>.
What is <xsl:apply-templates>
?
-
<xsl:apply-templates>
tells the XSLT processor:
“Go find matching nodes (based onselect
) and then apply the best matching template rules I’ve defined for them.” -
It’s template-driven, unlike
<xsl:for-each>
, which is more procedural.
Syntax
<xsl:apply-templates select="XPath_expression"/>
-
select
defines the nodes to which templates should be applied. -
The processor will look for
<xsl:template match="...">
rules that match those nodes.
Example XML
<books>
<book>
<title>XML Fundamentals</title>
<author>Alice Johnson</author>
</book>
<book>
<title>XSLT in Action</title>
<author>Bob Smith</author>
</book>
</books>
XSLT using <xsl:apply-templates>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<body>
<h2>Book List</h2>
<ul>
<!-- Apply templates to each <book> node -->
<xsl:apply-templates select="books/book"/>
</ul>
</body>
</html>
</xsl:template>
<!-- Template for each book -->
<xsl:template match="book">
<li>
<xsl:value-of select="title"/> -
<xsl:value-of select="author"/>
</li>
</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>
</ul>
</body>
</html>
Difference from <xsl:for-each>
-
xsl:for-each
: You write instructions directly inside the loop. -
xsl:apply-templates
: Delegates processing to matching templates, making code more modular and reusable.