xml
  1. xml-xsl-for-each

XML xsl:for-each

  • The xsl:for-each element in XSLT is used for iterating over a set of elements and performing the desired operation on each element.
  • The element is defined in the XSLT namespace with the prefix "xsl".

Syntax

The basic syntax for xsl:for-each element is as follows:

<xsl:for-each select="XPath expression">
   <!-- Desired operation on the selected elements -->
</xsl:for-each>

Here, the select attribute specifies the XPath expression to identify the set of elements to be iterated.

Example

Suppose we have an XML file containing a list of books:

<library>
   <book>
      <title>Harry Potter and the Philosopher's Stone</title>
      <author>J.K. Rowling</author>
      <year>1997</year>
   </book>
   <book>
      <title>The Hobbit</title>
      <author>J.R.R. Tolkien</author>
      <year>1937</year>
   </book>
</library>

We can use xsl:for-each to iterate over the book elements and print the title of each book:

<xsl:template match="/">
   <html>
      <body>
         <h2>Book Titles:</h2>
         <ul>
            <xsl:for-each select="library/book">
               <li><xsl:value-of select="title"/></li>
            </xsl:for-each>
         </ul>
      </body>
   </html>
</xsl:template>

Output

The output of the above example will be:

Book Titles:
- Harry Potter and the Philosopher's Stone
- The Hobbit

Explanation

The above example demonstrates the use of xsl:for-each to iterate over all book elements in the library element. Inside the xsl:for-each element, we have used the xsl:value-of element to print the title of each book.

Use

The xsl:for-each element is widely used in XSLT for iterating over a set of elements and performing some operation on them. It is commonly used for generating lists, tables, and other repeating elements in the output.

Important Points

  • We can use XPath expressions in the select attribute to choose the set of elements to iterate over.
  • We can nest xsl:for-each elements to iterate over multiple sets of elements.
  • If the select attribute is not specified, the xsl:for-each element will iterate over all child nodes of the current node.
  • Inside xsl:for-each, we can use other XSLT elements and functions to perform the desired operation on each selected element.

Summary

The xsl:for-each element in XSLT is used for iterating over a set of elements and performing some operation on each element. It allows us to process multiple elements in a single XSLT template. We can use XPath expressions in the select attribute to choose the set of elements to iterate over. Inside the xsl:for-each element, we can use other XSLT elements and functions to perform the desired operation on each selected element.

Published on: