XML sorting using XSL by Date
This is an approach to solve the date sorting problem in XML and XSLT. The date is a simple string "dd.mm.yyyy". The following example is a code snippet to solve this problem.
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.
The XML
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="style.xslt"?>
<birthdays>
<item>
<date>13.05.2005</date>
<title>John</title>
</item>
<item>
<date>06.02.2000</date>
<title>Steve</title>
</item>
<item>
<date>13.01.2007</date>
<title>Lisa</title>
</item>
<item>
<date>29.05.2010</date>
<title>Sarah</title>
</item>
</birthdays>
The XSLT
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="utf-8"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<xsl:template match="birthdays">
<h1>Birthdays</h1>
<ul>
<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" />
<li>
<xsl:value-of select="date" />
<br />
<xsl:value-of select="title" />
</li>
</xsl:for-each>
</ul>
</xsl:template>
</xsl:stylesheet>
You'll see the following output
The Output
Birthdays
-
29.05.2010
Sarah
-
13.01.2007
Lisa
-
13.05.2005
John
-
06.02.2000
Steve
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 dd.mm.yyyy, you'll need to change the values in substring function call above.