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

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

Just as conditions can be implemented as pure XPath expressions, so can loops. Direct sorting is impossible, however, because XPath has no statement for it. Even so, the available statement already offers considerable possibilities.

An XPath loop has this structure:

for $variable in eingabesequenz return rueckgabeausdruck

The variable declared after the for statement is local and instantiated for every loop iteration. The number of iterations equals the number of items in the sequence generated by the XPath expression after the in statement. Each iteration assigns the current item to the variable, which may, but need not, be referenced in the return expression.

Here is a simple example that successively stores numbers from 1 to 10 in variable $zahl, squares them and returns them as a sequence. The range is defined with operator to:

<xsl:value-of select="for $zahl in (1 to 10) return $zahl * $zahl"/>

The result is:

1 4 9 16 25 36 49 64 81 100

Two or more variables can easily be used in one statement:

<xsl:value-of select="for $zahl_1 in (1 to 10), $zahl_2 in (11 to 20) return $zahl_1 + $zahl_2"/>

This outputs the following number sequence:

12 13 14 15 16 17 18 19 20 21 13 14 15 16 17 18 19 20 21 22 14 15 16 17 18 19 20 21 22 23 15 16 17 18 19 20 21 22 23 24 16 17 18 19 20 21 22 23 24 25 17 18 19 20 21 22 23 24 25 26 18 19 20 21 22 23 24 25 26 27 19 20 21 22 23 24 25 26 27 28 20 21 22 23 24 25 26 27 28 29 21 22 23 24 25 26 27 28 29 30

The XPath loop also applies to the bookshop example. This time, local variable $i receives a node sequence processed successively, consisting of all <buch> in <buchhandel>. All book titles are output here, but without any punctuation:

<xsl:template match="/">
  <html>
    <head>
      <title>Buchhandel</title>
    </head>
    <body>
      <h2>Mein XML-Buchhandel</h2>
      <p><xsl:value-of select="for $i in buchhandel/buch return $i/buchtitel"/></p>
    </body>
  </html>
</xsl:template>

Additional tags cannot be output inside the loop, even with tricks. Changing the separator attribute value improves this, but also requires setting, on xsl:value-of, the attribute disable-output-escaping:

<xsl:value-of separator="&lt;br/&gt;" disable-output-escaping="yes" select="for $i in buchhandel/buch return $i/buchtitel"/>
 

At least this produces:

Where Wizards Stay Up Late Yet Another Hitchhiker's Guide to the Galaxy Unter Korallen und Haien

However, any umlauts in book titles are not represented by HTML entities.

Overall, the XPath loop is not an immediate direct replacement for xsl:for-each, or only with limitations. Its strength is returning a sequence of computed values generated in the loop.

   

back to top