XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round two / Sorting with xsl:sort / Loops in XSLT with xsl:for-each

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 2.)

A loop processes a series of values in succession. In this sense, xsl:apply-templates already acts as an implicit loop: its selected sequence is processed node by node. This requires corresponding template rules with suitable match attributes matching the nodes.

Alternatively, an explicit loop can execute without leaving its containing template. The instruction blocks needed to process the nodes or items are inside the loop instruction itself: xsl:for-each.

Like xsl:apply-templates, xsl:for-each uses a select attribute to construct its own sequence. Selected nodes are then processed in order by the internal instruction block:

<xsl:template match="daten">
  <table>
    <xsl:for-each select="datensatz">
      <tr><td><xsl:value-of select="."/></td></tr>
    </xsl:for-each>
  </table>
</xsl:template>

This template creates an HTML table as a literal result element, using the loop to output one row per <daten­satz> element in the selected sequence. Each <datensatz> element becomes the current node in turn, and xsl:value-of copies its value to the result sequence.

Here, xsl:for-each is not essential: the same result is easy to achieve with xsl:apply-templates and two separate templates. However, because xsl:for-each both constructs and processes its own sequence, it can treat an element inside the loop differently from an existing template rule elsewhere in the stylesheet.

For example, an explicit loop can build a table of contents for a large document, using headings that are processed differently elsewhere:

<xsl:template match="buchdokument">
  <h1>Inhaltsverzeichnis:</h1>
  <xsl:for-each select="//ueberschrift">
    <div><xsl:value-of select="."/></div>
  </xsl:for-each>
  <!-- normale Verarbeitung der Inhalte -->
  <xsl:apply-templates/>
</xsl:template>
<xsl:template match="ueberschrift">
...
</xsl:template>

This selects every <ueberschrift> node regardless of its depth. Rather than invoking the heading template used later for the document body, the sequence is processed locally by xsl:for-each itself.

In each iteration, the output element becomes the current node and the loop sequence is the current sequence. Functions fn:position() and fn:last() refer to that sequence. The current template rule remains that of the surrounding template.

Note:
An alternative solution uses template modes, introduced in Templates and template modes.

Simplifying the bookshop stylesheet

To simplify the stylesheet so that one template rule produces all output, xsl:for-each offers one approach.

Use xsl:for-each to declare a loop over every <buch> element:

...
<xsl:template match="/">
  <html>
    <head>
      <title>Buchhandel</title>
    </head>
    <body>
      <h2>Mein XML-Buchhandel</h2>
      <xsl:for-each select="buchhandel/buch">
        <p><xsl:value-of select="."/></p>
      </xsl:for-each>
    </body>
  </html>
</xsl:template>
...

Each <buch> becomes the active node in source order, and its string value is output in a <p> container. This admittedly crude approach shows in the output.

The loop’s sequence constructor can of course reproduce the formatting obtained with separate templates. Here, only books in category 'reisen' are output:

...
<xsl:for-each select="buchhandel/buch[@kat='reisen']">
  <p><b><xsl:value-of select="buchtitel"/></b> von <i><xsl:value-of select="buchautor" separator=", "/></i>;<br/><b>Verlag: </b><xsl:value-of select="buchverlag"/>, <xsl:value-of select="@ersch-jahr"/> – <i><xsl:value-of select="preis"/><xsl:text> </xsl:text><xsl:value-of select="preis/@waehrung"/></i></p>
</xsl:for-each>
...

The result looks almost as usual:

Yet Another Hitchhiker's Guide to the Galaxy von Adams, Douglas; Verlag: Spacetrotter Publishing, 2001 – 17.00 Dollar

Unterm Gipfelkreuz von Assmann, Peter; Verlag: Berg Verlag, 2002 – 14.00 Euro

Ganz oben von Hansen, Carl; Verlag:Berg Verlag, 1960 – 20.95 Euro

Sorting is also easy with this approach. The instruction xsl:sort used again here, however, has more to offer than shown so far.

Sorting sequences in xsl:for-each

We will now sort the book list without restricting categories, using several criteria: publisher, then author, then price in descending order.

Using xsl:sort in xsl:for-each works like its use in xsl:apply-templates, where these observations also apply. Here, three sort criteria are simply applied in succession:

<xsl:for-each select="buchhandel/buch">
  <xsl:sort select="buchverlag"/>
  <xsl:sort select="buchautor[1]"/>
  <xsl:sort select="preis" data-type="number" order="descending"/>
  <p><b><xsl:value-of select="buchtitel"/></b> von <i><xsl:value-of select="buchautor" separator=", "/></i>;<br/><b>Verlag: </b><xsl:value-of select="buchverlag"/>, <xsl:value-of select="@ersch-jahr"/> – <i><xsl:value-of select="preis"/><xsl:text> </xsl:text><xsl:value-of select="preis/@waehrung"/></i></p>
</xsl:for-each>

For authors, the familiar trick prevents xsl:sort, which expects a string rather than a node sequence as its sort key, from getting confused:

Unterm Gipfelkreuz von Assmann, Peter; Verlag: Berg Verlag, 2002 – 14.00 Euro

Bergwandern in den Alpen von Assmann, Peter; Verlag: Berg Verlag, 2002 – 14.00 Euro

Wenn der Berg ruft von Assmann, Peter; Verlag: Berg Verlag, 1989 – 12.00 Euro

Noch weiter oben von Hansen, Carl; Verlag: Berg Verlag, 1961 – 23.95 Euro

Books from “Berg Verlag” appear first, followed by those from EDV Verlag. Author sorting within publishers works, as does sorting by price within each author.

This defines a composite sort criterion. The first xsl:sort instruction is the primary criterion. Items it considers equal are sorted by the next, secondary criterion, and so on. A lower criterion never disrupts the ordering established by a higher one, making cascading sorts reliable.

   

back to top