xsl:for-each

Selects a set of nodes in the source document and instantiates the contained template once for each node in the set.

Format

Description

The select attribute is required and the pattern must evaluate to a node set. The XSLT processor instantiates the embedded template with the selected node as the current node and with a list of all selected nodes as the current node list.

By default, the new list of source nodes is processed in document order. However, you can use the xsl:sort instruction to specify that the selected nodes are to be processed in a different order. See xsl:sort.

The xsl:for-each instruction is useful when the result document has a regular, known structure. When you know that you want to instantiate the same template for each node in the current node list, the xsl:for-each instruction eliminates the need to find a template that matches each node.

Example

For example, suppose your source document includes the following XML:

The following stylesheet creates an HTML document that contains a list of authors. Each author is followed by the titles of the books the author wrote. It does not matter how many authors there are nor how many titles are associated with each author. The stylesheet uses the xsl:for-each instruction to process each author and to process each title associated with each author.

The result document looks like this:

 
Free Stylus Studio XML Training: