Let's explain <xsl:for-each>
in XML and XSLT with a simple example:
XML is a markup language used to structure and store data. It consists of elements that define the hierarchical structure of the data.
XSLT is a language for transforming XML documents into different formats, such as HTML, XML, or plain text. It uses templates and instructions to define how the transformation should occur.
<xsl:for-each>
in XSLT:<xsl:for-each>
is an XSLT instruction used to iterate over a selected set of nodes in the input XML document. It allows you to perform operations on each node in the selected set, such as outputting data or applying further transformations.
Let's say we have an XML document representing a bookstore with multiple books:
Example
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book> <title>Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> </book> <book> <title>Introduction to XML</title> <author>John Doe</author> <year>2010</year> </book> </bookstore>
Now, suppose we want to use XSLT to transform this XML into an HTML list (<ul>
) that displays the titles of all books.
Here's how you can use <xsl:for-each>
to achieve this transformation:
Example
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Template to match the root element --> <xsl:template match="/"> <html> <body> <h2>Book List</h2> <ul> <!-- Use for-each to iterate over each 'book' element --> <xsl:for-each select="bookstore/book"> <li> <xsl:value-of select="title"/> </li> </xsl:for-each> </ul> </body> </html> </xsl:template> </xsl:stylesheet>
XSLT Structure:
<xsl:stylesheet>
defines the XSLT document with its version and namespace.xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
declares the XSLT namespace.Template and <xsl:for-each>
Usage:
<xsl:template match="/">
: This template matches the root element of the XML document (/
). It defines the structure of the HTML output.<xsl:for-each select="bookstore/book">
selects each <book>
element within <bookstore>
.<xsl:value-of select="title"/>
inside <xsl:for-each>
retrieves and outputs the text content of the <title>
element for each <book>
.When this XSLT transformation is applied to the XML document provided earlier, the output HTML will be:
Example
<html> <body> <h2>Book List</h2> <ul> <li>Harry Potter</li> <li>Introduction to XML</li> </ul> </body> </html>
<xsl:for-each>
iterates over a selected set of nodes in the XML document and allows you to perform operations on each node in the set.In this example, <xsl:for-each>
was used to iterate through each <book>
element in the XML document and output the <title>
of each book as an HTML list item (<li>
). This demonstrates how XSLT can be used to transform XML data into structured HTML output by iterating over and processing elements in the input document.