O'Reilly logo

Java and XSLT by Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Looping and Sorting

As shown throughout this chapter, you can use <xsl:apply-templates ...> to search for patterns in an XML document. This type of processing is sometimes referred to as a " data driven” approach because the data of the XML file drives the selection process. Another style of XSLT programming is called "template driven,” which means that the template’s code tends to drive the selection process.

Looping with <xsl:for-each>

Sometimes it is convenient to explicitly drive the selection process with an <xsl:for-each> element, which is reminiscent of traditional programming techniques. In this approach, you explicitly loop over a collection of nodes without instantiating a separate template as <xsl:apply-templates> does. The syntax for <xsl:for-each> is as follows:

<xsl:for-each select="president">
  ...content for each president element
</xsl:for-each>

The select attribute can contain any XPath location path, and the loop will iterate over each element in the resulting node set. In this example, the context is <president> for all content within the loop. Nested loops are possible and could be used to loop over the list of <vicePresident> elements.

Sorting

Sorting can be applied in either a data-driven or template-driven approach. In either case, <xsl:sort> is added as a child element to something else. By adding several consecutive <xsl:sort> elements, you can accomplish multifield sorting. Each sort can be in ascending or descending order, and the data type for sorting ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required