Chapter 6. Sorting and Grouping Elements
By now, I hope you’re convinced that you can use XSLT to convert big piles of XML data into other useful things. Our examples to this point have pretty much gone through the XML source in what’s referred to as document order. We’d like to go through our XML documents in a couple of other common ways, though:
We could sort some or all of the XML elements, then generate output based on the sorted elements.
We could group the data, selecting all elements that have some property in common, then sorting the groups of elements.
We’ll give several examples of these operations in this chapter.
Sorting Data with <xsl:sort>
The simplest way to rearrange our XML elements is to use the <xsl:sort>
element. This element temporarily rearranges a collection of elements based on criteria we define in our stylesheet.
Our First Example
For our first example, we’ll have a set of U.S. postal addresses that we want to sort. (No chauvinism is intended here; obviously every country has different conventions for mailing addresses. We just needed a short sample document that can be sorted in many useful ways.) Here’s our original document:
<?xml version="1.0"?> <addressbook> <address> <name> <title>Mr.</title> <first-name>Chester Hasbrouck</first-name> <last-name>Frisby</last-name> </name> <street>1234 Main Street</street> <city>Sheboygan</city> <state>WI</state> <zip>48392</zip> </address> <address> <name> <first-name>Mary</first-name> <last-name>Backstayge</last-name> ...
Get XSLT 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.