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..
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.
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" />
Check this issue for the problem's solution. It uses XSLT sort to sort XML by the dates in the XML.
Date in the xml is a string. Unless the date always looks like this: yyyy-mm-dd you really can't sort it in the correct order.
So this is the correct way:
<xsl:sort select="newsDate" order="ascending" />
It will works like a charm.
if you have control over the xml-generation:
Input:
<date1> 2010-10-17+02:00 </date1>
Transform:
<date1 number="{translate(substring-before(date1,'+'),'-','')}"
<xsl:value-of select="date1"/>
</date1>`
Output:
<date1 number="20101017">2010-10-17+02:00</date1>
than you can use like usual
<xsl:sort order="descending" select="@number" data-type="number"/>
Greetz
You can sort the date1 field by using the US date format to create a year/month/date string, then sorting that descending. In the xsl:for-each tag you would add this:
<xsl:sort select="ddwrt:FormatDateTime(string(@date1),1033,'yy/MM/dd')" order="descending" />