O'Reilly logo

Beginning XSLT and XPath: Transforming XML Documents and Data by Ian Williams

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

Chapter 5. Sorting and Grouping

Sorting content in various orders and grouping it into categories is standard fare in all manner of lists and reports. XSLT provides several useful tools that will help you get the results you want.

The sort instruction can be used in many stylesheet contexts with several sort options, and the <xsl:for-each-group> instruction makes it possible to group elements in a number of ways using very compact syntax.

In this chapter you'll do the following:

  • Examine the options available to you for sorting and grouping content using <xsl:sort>, <xsl:perform-sort>, and <xsl:for-each-group>.

  • Learn about the significance of datatypes and languages in sorting.

  • See how to use variables in attribute value templates to create runtime values.

  • Process part of a Shakespearian play marked up in XML.

Sorting Content

In earlier chapters you have used <xsl:sort> a couple of times with the default behavior, which is to sort as text, and to order it A-Z. Because that works well on many occasions, I did not discuss order options, multiple instructions, and so on. This section will fill in some details.

The <xsl:sort> instruction provides a single sort key component in a possible set of keys known as a sort key specification. For example, in the following code snippet, each of the individual sort instructions is a key component, and the pair of components together make up the key specification:

<xsl:for-each select="//product"> <xsl:sort select="@store"/> <xsl:sort select="@sku"/> ... ...

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