Home arrow XML arrow Page 6 - XSL Basics (part 2)

Sorting Things Out - XML

In this concluding article, expand your XSLT vocabulary by exploring conditional constructs, loops, variables, and numbering, together with examples and illustrations of how these programming capabilities can substantially simplify your XSLT experience.

  1. XSL Basics (part 2)
  2. Mercury Rising
  3. The Number Game
  4. A Node By Any Other Name
  5. Looping The Loop
  6. Sorting Things Out
  7. Be Cool
  8. Flavour Of The Month
  9. Endgame
By: icarus, (c) Melonfire
Rating: starstarstarstarstar / 6
August 31, 2001

print this article


Now, if you've been paying attention, you'll have noticed a small problem with the preceding example. Though the XML document putatively contains a list of someone's top five movies, ranked according to the "rank" element, the stylesheet does not process this data and prints the movies in the order in which it finds them.

It's to resolve precisely this kind of situation that XSLT also includes a powerful sorting mechanism, which can be used to rearrange the data within the document in a specific order. The <xsl:sort> instruction uses the "select" attribute to select the elements against which to sort the data, as also whether to use ascending or descending order.

Let's rewrite the template rule above to present the top five movies in correct order:

<xsl:template match="/top_five"> <xsl:for-each select="movie"> <xsl:sort select="rank" /> <li><xsl:value-of select="name" /></li> <br /> <font size="2"><xsl:value-of select="cast" /> | <xsl:value-of select="director" /></font> </xsl:for-each> </xsl:template>
In case I wanted to reverse the order - just to confuse readers and because I'm a nasty evil person - I could add an "order" attribute to specify the sort order:

<xsl:template match="/top_five"> <xsl:for-each select="movie"> <xsl:sort select="rank" order="descending" /> <li><xsl:value-of select="name" /></li> <br /> <font size="2"><xsl:value-of select="cast" /> | <xsl:value-of select="director" /></font> </xsl:for-each> </xsl:template>
XSLT allows you to specify more than one <xsl:sort> instruction, so that it becomes possible to sort by more than one key - for example, rank followed by name followed by director.

>>> More XML Articles          >>> More By icarus, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Google Docs and Xpath Data Functions
- Flex Array Collection Sort and Filtering
- The Flex Tree Control
- Flex List Controls
- Working with Flex and Datagrids
- How to Set Up Podcasting and Vodcasting
- Creating an RSS Reader Application
- Building an RSS File
- An Introduction to XUL Part 6
- An Introduction to XUL Part 5
- An Introduction to XUL Part 4
- An Introduction to XUL Part 3
- An Introduction to XUL Part 2
- An Introduction to XUL Part 1
- XML Matters: Practical XML Data Design and M...

Developer Shed Affiliates


Dev Shed Tutorial Topics: