Sort XML Attribute using XSLT | Sort XML by Date using XSLT

This is an approach to solve the date sorting problem in XML and XSLT. This article gives an example to sort XML attribute using XSLT. The attribute is date here – so it XSLT sorts the XML by Date. The date is a simple string “”. The following example is a code snippet to solve this problem.

Code to sort XML attribute using XSLT

To check this, copy the xml below in data.xml, copy the xslt code in style.xslt. Store them in same directory and view the XML in Browser.


          <?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="style.xslt"?>


          <?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
<xsl:output method="html" encoding="utf-8"
 doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
<xsl:template match="birthdays">
<xsl:for-each select="item">
<xsl:sort select="normalize-space(substring(date,7,4))" order="descending" />
<xsl:sort select="normalize-space(substring(date,4,2))" order="descending" />
<xsl:sort select="normalize-space(substring(date,0,2))" order="descending" />
<xsl:value-of select="date" />
<br />
<xsl:value-of select="title" />

You’ll see the following output

The Output


  • 29.05.2010
  • 13.01.2007
  • 13.05.2005
  • 06.02.2000

The parameter order=”descending” sorts the date in descending order. To sort in ascending, change descending to ascending. Normalize space is used to ignore or trim the leading or trailing spaces to help perform the sort function correctly. Substring chooses the particular part of date from the date string. If your date is in a format other than, you’ll need to change the values in substring function call above.

Running into issues?! Discuss below.

Leave a Reply

Your email address will not be published. Required fields are marked *