Name
<xsl:for-each>
Synopsis
<xsl:for-each select="
pattern
"/>
Description
The <xsl:for-each>
directive allows you to select any number of
identical siblings in an XML document. For example, consider the following
XML
document:
<book> <chapter> <title>A Mystery Unfolds</title> <paragraph>It was a dark and stormy night...</paragraph> </chapter> <chapter> <title>A Sudden Visit</title> <paragraph>Marcus found himself sleeping...</paragraph> </chapter> </book>
Note there are two <chapter>
siblings in the document.
Let’s assume we want to provide an HTML numbered list for each
<title>
element that is the direct child of a <chapter>
element, which in turn has a <book>
element as a parent. The
following XSL
performs the task:
<xsl:template match="book> <ol> <xsl:for-each select="chapter"> <li><xsl:process select="title"></li> </xsl:for-each> </ol> </xsl:template>
After formatting, here is what the result looks like:
<ol> <li>A Mystery Unfolds</li> <li>A Sudden Visit</li> </ol>
The XSL processor processes a <title>
element in
each <chapter>
element that is the child of a <book>
element. The result is a list for each chapter that could be
used for a table of contents.
Get Webmaster in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.