Sort XML by date using xslt

For this, we just use the simple 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>

And the xslt code would be something like this

<?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>

Output

Birthdays

  • 29.05.2010
    Sarah
  • 13.01.2007
    Lisa
  • 13.05.2005
    John
  • 06.02.2000
    Steve
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.