Chapter 8. Sorting Things Out

Sometimes nodes don’t come to you in a convenient order. XSLT’s sort instruction element allows you to sort nodes in alphabetical or numerical order. You can also use sort to sort nodes in ascending (a, b, c) or descending (z, y, x) order.

This chapter walks you through a brief exploration of sort. You can also read about sorting in Section 10 of the XSLT specification. I’ll start, as usual, with a simple example.

Simple Ascending Sort

If you look at Example 8-1, the document europe.xml in examples/ch08, you’ll notice that the European states are not listed in alphabetical order.

Example 8-1. Unalphabetized European countries
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="pretty.xsl" type="text/xsl"?> <europe> <state>Belgium</state> <state>Germany</state> <state>Finland</state> <state>Greece</state> <state>Ireland</state> <state>Luxembourg</state> <state>Portugal</state> <state>Spain</state> <state>Andorra</state> <state>Belarus</state> <state>Monaco</state> <state>Sweden</state> <state>United Kingdom</state> <state>Austria</state> <state>Malta</state> <state>Vatican City</state> <state>Bulgaria</state> <state>Bosnia-Herzegovina</state> <state>Cyprus</state> <state>France</state> <state>Estonia</state> <state>Italy</state> <state>Hungary</state> <state>Latvia</state> <state>Ukraine</state> <state>Lithuania</state> <state>Moldova</state> <state>Denmark</state> <state>Poland</state> <state>Romania</state> <state>Slovenia</state> <state>The ...

Get Learning 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.