6 - Sorting with <xsl:sort>

XSLT script: iliad6.xsl
<xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>

<xsl:template match="/">

<table border="1" cellpadding="3">
	<th>Name of Character</th>
	<th>Line #</th>
	<xsl:for-each select="document/poem/line/name">
	<xsl:sort select="current()" order="ascending" data-type="text" />
		<tr>
		<td>
			<xsl:value-of select="current()"/>
		</td>
		<td>
			<xsl:value-of select="../@num"/>
		</td>
		</tr>
	</xsl:for-each>
</table>

</xsl:template>

</xsl:stylesheet>
The <xsl:sort> command must be used within a <xsl:for-each> command.

As in example 4, the <xsl:for-each> command tells the browser to find each <name> XML tag. However, by placing the <xsl:sort> command directly after the <xsl:for-each> command, the browser is told to sort the findings alphabetically.

[Review the XML document]

The <xsl:sort> command has a number of attributes which may be set to various values:

Attribute Possible settings Description
select [node name] The node to be sorted
order ascending
descending
ascending sorts from A-Z or lowest number to highest;
descending sorts oppositely. Default is ascending.
case-order upper-first
lower-first
upper-first sorts upper-case letters first and lower-case letters second;
lower-first sorts oppositely.
data-type text
number
Type of data being sorted. Defeault is text.
lang [a language-code: for example, "en"] The language of the data being sorted.

RESULTS of iliad6.xsl
Name of Character Line #
Achaeans2
Achilles1
Achilles7
Atreus7
Hades3
Peleus1
Zeus5
The names are sorted in alphabetical order.