Quackit Logo

FREE Hosting!

With every domain name you register with ZappyHost, you get FREE hosting.

$1.99 Domain Names

With every new non-domain purchase thru ZappyHost, you get a domain name for only $1.99.

XSLT <for-each> Element

Print Version

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?

  1. Link to this page (copy/paste into your own website or blog):
  2. Add this page to your favorite social bookmarks sites:
               
  3. Add this page to your Favorites

Oh, and thank you for supporting Quackit!