Stylus Studio XML Editor

Table of contents

Appendices

8 Repetition

Repetition

< for-each
   select= node-set-expression >
   <-- Content: sort* -->
< /for-each>

When the result has a known regular structure, it is useful to be able to specify directly the template for selected nodes. The xsl:for-each instruction contains a template, which is instantiated for each node selected by the Expression specified by the select attribute. The select attribute is required. The expression must evaluate to a node-set. The template is instantiated with the selected node as the Current Node, and with a list of all of the selected nodes as the Current Node List. The nodes are processed in document order, unless a sorting specification is present (see [Sorting]).

For example, given an XML document with this structure

<customers>
  <customer>
    <name>...</name>
    <order>...</order>
    <order>...</order>
  </customer>
  <customer>
    <name>...</name>
    <order>...</order>
    <order>...</order>
  </customer>
</customers>

the following would create an HTML document containing a table with a row for each customer element

<xsl:template match="/">
  <html>
    <head>
      <title>Customers</title>
    </head>
    <body>
      <table>
	<tbody>
	  <xsl:for-each select="customers/customer">
	    <tr>
	      <th>
		<xsl:apply-templates select="name"/>
	      </th>
	      <xsl:for-each select="order">
		<td>
		  <xsl:apply-templates/>
		</td>
	      </xsl:for-each>
	    </tr>
	  </xsl:for-each>
	</tbody>
      </table>
    </body>
  </html>
</xsl:template>