How to use XSLT to sort XML data by Multiple Elements

XSLT  (EXtensible Sytlesheet Language Transformations) is a tool that can be used to transform XML documents into other formats most commonly of which is XHTML. XSLT is a stylesheet that defines how to display or output the data from the XML. Using XSLT you can sort, filter, and manipulate the data as needed iterating of data elements and their child elements. Below is a short example of how to sort an XML data file based on 2 elements.

To start things off we need an xml data file. In our example we are going to use books. You will notice that in addition to the xml data we specify the xml-stylesheet to utilize which we will create next.

	Patrick Rothfuss
	The Name of the Wind		
	Trudi Canavan
	The Magicain's Guild		
	Trudi Canavan
	The Magicain's Apprentice		
	Jim Butcher
	First Lord's Fury		
	Jim Butcher
	Brandon Sanderson

Next we will create an XSL Stylesheet that will be used to transform the XML Data into a XHTML page that displays the information in a table sorted by author followed by the title.

My Books

Title Author Publisher Year

In the above example we define the style sheet to iterate over each book element in the xml using the xsl:for-each tag. Then we immediately tell it to sort on the author field and secondly by the title field by use of the xsl:sort tag.

The end result is an html table as shown below:

Title Author Publisher Year
Warbreaker Brandon Sanderson TOR 2009
Changes Jim Butcher ROC 2010
First Lord’s Fury Jim Butcher ACE 2090
The Name of the Wind Patrick Rothfuss DAW 2007
The Magicain’s Apprentice Trudi Canavan Orbit 2009
The Magicain’s Guild Trudi Canavan EOS 2004

You can sort on as many elements as you want simply adding addtional xsl:sort tags. Full information on the available properties like order can be found at w3schools

// HTML/CSS // XML // XSLT //

Comments & Questions

Add Your Comment