Written some cool source code? Upload it to Programmer's Heaven.
*/
*/

How to Sort XML by Multiple Attributes using XSLT

How to sort XML by multiple attributes using XSLT?

The example shows how to sort XML data by multiple attributes @ISBN and @author are held within the same element <title>. The XSL stylesheet will display the sorted elements in a HTML table.

Create an XML document and link it to a XSL stylesheet.

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="sort.xsl"?>
<books>
   <book>  
        <title ISBN="0321173481" author="Michael R. Sweet">
	OpenGL Programming Guide Fourth Edition</title>		
	<publisher>Addison-Wesley</publisher>
	<year>2004</year>
   </book>
   <book>
	<title ISBN="0849371643" author="Gerald Farin">
	Curves and Surfaces for CAGD: A Practical Guide</title>
	<publisher>Academic Press</publisher>
	<year>2002</year>
   </book>
   <book>
	<title ISBN="1558606696" author="David Rogers">
	An Introduction to NURBS: With Historical Perspective</title>
	<publisher>Academic Press</publisher>
	<year>2001</year>
   </book>
   <book>
	<title ISBN="1568810849" author="Gerald Farin">
	NURBS: From Projective Geometry to Practical Use</title>
	<publisher>A K Peters</publisher>
	<year>1999</year>
   </book>
</books>


Create a XSL stylesheet.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8"/>
<xsl:template match="/">
<html>
<head><title>Books</title>
</head>
<body>
<table width="100%" border="1">
 <THEAD>
   <TR>
     <TD width="40%"><B>Title</B></TD>
     <TD width="10%"><B>Publisher</B></TD>
   </TR>
 </THEAD> 
 <TBODY>
   <xsl:for-each select="books/book">
     <xsl:sort select="title/@ISBN" />
     <xsl:sort select="title/@author" />
   <TR>	
     <TD width="40%"><xsl:value-of select="title/@ISBN" /></TD>   
     <TD width="10%"><xsl:value-of select="title/@author" /></TD>
   </TR>
  </xsl:for-each>
 </TBODY>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>


By adding more <xsl:sort> will sort the output by the first then by the second attribute specified. Identical attribute values are sorted in the order they appear in the XML document.

<xsl:sort select="@ISBN" data-type="number" />
<xsl:sort select="@author" />


Output:

ISBN
0321173481 
0849371643  
1558606696  
1568810849


Author
Michael R. Sweet 
Gerald Farin
David Rogers
Gerald Farin


Back to XML FAQ
corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.
Resource Listings