Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML

Print Version

XSLT <sort> Element

The XSLT <xsl:sort> element allows you to sort the output of the <xsl:for-each> element.

<xsl:sort> Example

Here, we use <xsl:for-each> to loop through each "tutorial" element, and <xsl:sort> to sort by the "name" node. We then use the <xsl:value-of> to extract data from the "name" node.

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

<xsl:template match="/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="tutorials">
  <xsl:for-each select="tutorial">
    <xsl:sort select="name"/>
    <xsl:value-of select="name"/><xsl:element name="br"/>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Result

So, let's see what would happen if we applied the above XSLT document to the following XML document:

<tutorials>
  <tutorial>
    <name>XML Tutorial</name>
    <url>http://www.quackit.com/xml/tutorial</url>
  </tutorial>
  <tutorial>
    <name>HTML Tutorial</name>
    <url>http://www.quackit.com/html/tutorial</url>
  </tutorial>
</tutorials>

Before:

This is how the contents would be displayed before applying the <xsl:sort> element:

XML Tutorial
HTML Tutorial

After:

This is how the contents would be displayed after applying the <xsl:sort> element:

HTML Tutorial
XML Tutorial

Enjoy this website?

  • Share
  • Add this page to your Favorites
  • Link to this page (copy/paste into your own website or blog):
  • Link to Quackit using one of these banner ads.
  • Help support Quackit by making a donation

Oh, and thank you for supporting Quackit!

© Copyright 2000 - 2010 Quackit.com