Name
<xsl:for-each>
Synopsis
The <xsl:for-each> directive allows you to
select any number of nodes in an XML document that match the same
expression given by select. 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 template 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 XSLT processor processes a <title>
element in each <chapter> element that is
the child of a <book> element. The result is
a numbered list of chapters that could be used for a table of
contents.
<xsl:for-each select="node-set-expression"/>Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access