Export (0) Print
Expand All

<xsl:for-each> Element

Applies a template repeatedly — that is, to each node in a set.

<xsl:for-each
  select = Expression
</xsl:for-each>

select
Required. Expressions (XML) evaluated on the current context to determine the set of nodes to iterate over.

The <xsl:for-each> element establishes the context for iteration. The XSLT transformation instructions within this loop are to be applied to the selected nodes. Each source element selected by <xsl:for-each> becomes a new context against which any pattern matching within the <xsl:for-each> occurs.

The XSLT file in this example defines the structure of an output document. The output is a top-level HTML element containing <BODY> and <TABLE> elements. The table contains repeated rows for each customer. The XSLT file also uses templates to create <TD> elements for the name, address, and phone source elements.

XML File (customers.xml)

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="foreach.xsl" ?>
<customers>
   <customer>
      <name>John Smith</name>
      <address>123 Oak St.</address>
      <state>WA</state>
      <phone>(206) 123-4567</phone>
   </customer>
   <customer>
      <name>Zack Zwyker</name>
      <address>368 Elm St.</address>
      <state>WA</state>
      <phone>(206) 423-4537</phone>
   </customer>
   <customer>
      <name>Albert Aikens</name>
      <address>368 Elm St.</address>
      <state>WA</state>
      <phone>(206) 423-4537</phone>
   </customer>
   <customer>
      <name>Albert Gandy</name>
      <address>6984 4th St.</address>
      <state>WA</state>
      <phone>(206) 433-4547</phone>
   </customer>
   <customer>
      <name>Peter Furst</name>
      <address>456 Pine Av.</address>
      <state>CA</state>
      <phone>(209) 765-4321</phone>
   </customer>
   <customer>
      <name>Dan Russell</name>
      <address>9876 Main St.</address>
      <state>PA</state>
      <phone>(323) 321-7654</phone>
   </customer>
</customers>

XSLT File (foreach.xsl)

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

  <xsl:template match="/">
    <HTML>
      <BODY>
        <TABLE>
          <xsl:for-each select="customers/customer">
            <xsl:sort select="state" order="descending"/>
            <xsl:sort select="name"/>
            <TR>
              <TD><xsl:value-of select="name" /></TD>
              <TD><xsl:value-of select="address" /></TD>
              <TD><xsl:value-of select="phone" /></TD>
            </TR>
          </xsl:for-each>
        </TABLE>
      </BODY>
    </HTML>
  </xsl:template>

</xsl:stylesheet>

Output

This is the formatted output:

Formatted output

This is the processor output:

<HTML>
<BODY>
<TABLE>
<TR>
<TD>Albert Aikens</TD>
<TD>368 Elm St.</TD>
<TD>(206) 423-4537</TD>
</TR>
<TR>
<TD>Albert Gandy</TD>
...
</TR>
</TABLE>
</BODY>
</HTML>




Build Date:

2012-08-02
Show:
© 2014 Microsoft