Skip to content

XSLT <xsl:sort> Element

How to use the XSLT <xsl:sort> element to define sorting criteria for XML data, including attributes like select, order, data-type, and case-order with practical examples.

The <xsl:sort> element is used to specify a sort criterion for the output.

<xsl:sort> Element

Syntax

The syntax of <xsl:sort> is as follows:

<xsl:sort 
	select=string-expression
	lang={nmtoken}
	data-type={"text"|"number"|QName}
	order={"ascending"|"descending"}
	case-order={"upper-first"|"lower-first"}>
</xsl:sort>

Attributes

The table describes the meaning of the attributes of <xsl:sort>:

Name Description
select It is used for sorting key of the node.
lang It specifies language alphabet used to determine sort order.
data-type It specifies data-type of the text.
order It is used to specify the sorting order. By default sorting order is ascending order.
case-order It is used to specify sorting order of string by capitalization. Default is "upper-first".

Example

Let's see an example:

books.xmlxml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>

<bookstore>
	<book category="children">
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year>
		<price>29.99</price>
	</book>
	<book category="web">
		<title lang="en">XQuery Tips</title>
		<author>Tom Nolan</author>
		<year>2022</year>
		<price>39.99</price>
	</book>
	<book category="web">
		<title lang="en">Learn XML</title>
		<author>Tutorial Reference</author>
		<year>2022</year>
		<price>9.99</price>
	</book>
</bookstore>
books.xslxml
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
	<html>
		<body>
			<h2>The Bookstore</h2>
			<table border="1">
				<tr bgcolor="#6565d5">
					<th>Title</th>
					<th>Author</th>
					<th>Year</th>
					<th>Price</th>
				</tr>  
				<xsl:for-each select="bookstore/book">
				<xsl:sort select="author"/>
					<tr>
						<td><xsl:value-of select="title"/></td>
						<td><xsl:value-of select="author"/></td>
						<td><xsl:value-of select="year"/></td>
						<td><xsl:value-of select="price"/></td>
					</tr>
				</xsl:for-each>
			</table>
		</body>
	</html>
</xsl:template>

</xsl:stylesheet>
Navigation