XSLT xsl:for-each
In XSLT (Extensible Stylesheet Language Transformations), the xsl:for-each
element is used to process a selected set of nodes in the input XML document. It allows you to apply a template or perform a specific action for each node that matches the specified XPath expression within the xsl:for-each
.
The basic syntax of the xsl:for-each
element is as follows:
<xsl:for-each select="xpath-expression">
<!-- Code block to apply or execute for each selected node -->
</xsl:for-each>
In this structure:
- The
select
attribute of thexsl:for-each
element specifies the XPath expression that selects the nodes to be processed. The expression should evaluate to a node-set. - The code block within the
xsl:for-each
element is applied or executed once for each node that matches the XPath expression.
Here’s an example of using xsl:for-each
to iterate through a list of books and generate an HTML table with book titles and authors:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
In this example, assuming the XML input contains a list of <book>
elements with child elements <title>
and <author>
, the XSLT transformation will iterate through each <book>
element using xsl:for-each
, and for each iteration, it will generate an HTML table row (<tr>
) containing the book title and author.
The xsl:for-each
element is a powerful tool in XSLT for processing multiple nodes based on a common selection criterion. It allows you to loop through node-sets and apply templates or perform actions to generate the desired output based on the structure of the input XML document.