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: 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: 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.
blog comments powered by Disqus |