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"/> ... ...

Get Beginning XSLT and XPath: Transforming XML Documents and Data now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.