Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML

Print Version

XSLT <for-each> Element

The XSLT <xsl:for-each> element allows you to loop through multiple nodes that match the selection criteria. This in turn, enables you to retrieve data from these nodes.

For example, imagine if our XML file had two elements called "name" - each under the "tutorial" element. Like this:

<?xml version="1.0" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="tutorials.xsl"?>
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<name>Homer Flinstone</name>
<url>http://www.quackit.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<name>Fred Simpson</name>
<url>http://www.quackit.com/html/tutorial</url>
</tutorial>
</tutorials>

To extract data from both "name" elements, we can use <xsl:for-each> in conjunction with <xsl:value-of>.

<xsl:for-each> Example

Here, we use <xsl:for-each> to loop through each "name" element, and <xsl:value-of> to extract data from each node.

Note the value of the select attribute ("."). This expression specifies the current node. The <xsl:element name="br"/> element/attribute is there simply for readibility purposes - it provides a line break after each iteration.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="tutorial">
    <xsl:for-each select="name">
      <xsl:value-of select="."/><xsl:element name="br"/>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

Enjoy this website?

  • Share
  • Add this page to your Favorites
  • Link to this page (copy/paste into your own website or blog):
  • Link to Quackit using one of these banner ads.
  • Help support Quackit by making a donation

Oh, and thank you for supporting Quackit!

© Copyright 2000 - 2010 Quackit.com