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 “dd.mm.yyyy”. 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.

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.

Running into issues?! Discuss below.

About the Author

aditya bajaj
Music and Blogging get my love.

Be the first to comment on "Sort XML Attribute using XSLT | Sort XML by Date using XSLT"

Leave a comment

Your email address will not be published.


*