The <xsl:for-each> Element
If you want to process all the nodes that match a
certain criteria, you can use the <xsl:for-each>
element. Be aware that
this isn’t a traditional for
loop;
you can’t ask the XSLT processor to do something like this:
for i = 1 to 10 do
The <xsl:for-each>
element lets you select a set of nodes, and then do something with
each of them. Let me mention again that this is not the same as a
traditional for
loop. Another
important point is that the current node changes with each iteration
through the <xsl:for-each>
element. We’ll go through some examples to illustrate this.
Note
You can use the XSLT 2.0 to
operator to do something similar (select="1 to 10"
). When you’re working
with XSLT, it’s better to think of <xsl:for-each>
as an iterator rather
than a traditional for
loop.
<xsl:for-each> example
Here’s a sample that selects all <section>
elements inside a <tutorial>
element and then uses a
second <xsl:for-each>
element to select all the <panel>
elements inside each
<section>
element:
<xsl:template match="tutorial"> <xsl:for-each select="section"> <h1> <xsl:text>Section </xsl:text> <xsl:value-of select="position()"/> <xsl:text>. </xsl:text> <xsl:value-of select="title"/> </h1> <ul> <xsl:for-each select="panel"> <li> <xsl:value-of select="position()"/> <xsl:text>. </xsl:text> <xsl:value-of select="title"/> </li> </xsl:for-each> </ul> </xsl:for-each> </xsl:template>
Given this XML document:
<tutorial> <section> <title>Gene Splicing for Young People</title> <panel> <title>Introduction</title> ...
Get XSLT, 2nd 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.