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 --> <list> <item maker="Friendly Foods"> <name>Granola Crust Pizza</name> <price>11.99</price> </item> <item maker="Ammondale Farms"> <name>Yogurt</name> <price>1.00</price> </item> <item maker="Ammondale Farms"> <name>ChocoFlakes</name> <price>3.49</price> </item> </list>
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 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.