Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem in sorting xml by date<xsl:sort select=""/>

Tags:

xml

xslt

I am trying to sort my xml by date but its not working my xml and xsl r like this

<xsl:template match="/">
    <xsl:for-each select="news/item">
                        <xsl:sort select="date1" order="descending" />                                     

                          <xsl:value-of select="date1"/>                                

                  </xsl:for-each> 
</xsl:template>

MYXML

<news>
 <item>
<date1>January 1, 2010</date1>
 </item>
 <item>
  <date1>November 29, 2009</date1>
</news>


         Its displaying the result but not in sorted way..
like image 557
AB. Avatar asked Jul 02 '26 04:07

AB.


2 Answers

You can try to use something like this:

<xsl:template match="/"> 
  <xsl:for-each select="news/item"> 
    <xsl:sort select="xs:date(date1)" order="descending" />
    <xsl:value-of select="date1"/>                                 
  </xsl:for-each>  
</xsl:template> 

Although, if you have control over the XML generation, I'd also put something like:

<date1 isoValue="20100101">January 1, 2010</date1>

And then use

<xsl:sort select="xs:date(date1/@isoValue)" order="descending" />

Note the xs namespace below:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">
like image 64
Paulo Santos Avatar answered Jul 05 '26 18:07

Paulo Santos


xsl-sort does not "know" how to sort dates. It will use default to text sort, though you can specify numeric sort by using the data-type attribute.

There are several approches to solve this - add an attribute or change how you output the date to the source XML, so you have to a representation you can sort numerically.

like image 38
Oded Avatar answered Jul 05 '26 18:07

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!