Sorting and Grouping Repeating Data with XSLT

If you do not have the luxury of controlling the SQL statement producing the XML information you are working with, XSLT 1.0 can be used to sort and group any information in an XML document. The <xsl:sort> action allows you to sort your node lists—either selected by <xsl:for-each> or matched through <xsl:apply-templates> —based on any string or number values that they contain. However, such a claim cannot be made for grouping repeating information. In short, there is no <xsl:group> action that provides this capacity.

Sorting on Element or Attribute Values

The <xsl:sort> action allows you to sort by string or number values as a part of your transformation. Let’s look at some examples of how you can put this action to use. Suppose we have a simple shopping list document like this:

<!-- ShoppingList.xml -->
  <item maker="Friendly Foods">
    <name>Granola Crust Pizza</name>
  <item maker="Ammondale Farms">
  <item maker="Ammondale Farms">

We can create a stylesheet to transform the shopping list into an equivalent structure ordered by the name of the items. To use <xsl:sort>, you include it as a child element of either <xsl:apply-templates> or <xsl:for-each>. The following SortByName.xsl stylesheet illustrates using <xsl:sort> with <xsl:apply-templates> to cause the XSLT processor to process the <item> ...

Get Building Oracle XML Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.