Search code examples
xmlxsltrfc822

Sort XML by RFC-822 date format using XSL


Does anyone know of a way to do this kind of sorting in XSL?

Here's what I have so far but it only sorts by day and ignores the rest of the date.

      <xsl:apply-templates select="item">
          <xsl:sort select="pubDate" data-type="text" order="descending"/>
      </xsl:apply-templates>

Solution

  • Thanks for the quick responses guys. Got me going in the right direction. Managed to solve it! Found a useful link http://blog.mastykarz.nl/how-to-do-it-rss-aggregation-merging-multiple-xml-files-using-xslt/

    I was using XSLT Version 2.0. Just a case using a variable to substitute in the MMM months and sub-stringing the date down.

    SOLUTION

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:variable name="Months" select="'Jan;Feb;Mar;Apr;May;Jun;Jul;Aug;Sep;Oct;Nov;Dec'"/>
    
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="channel">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()[not(preceding-sibling::item) and not(self::item)]"/>
            <xsl:apply-templates select="item">
                <!-- year -->
            <xsl:sort select="substring(pubDate, 13, 4)" order="descending" data-type="number"/>
            <!-- month -->
            <xsl:sort select="string-length(substring-before($Months, substring(pubDate, 9, 3)))" order="descending" data-type="number"/>
            <!-- day -->
            <xsl:sort select="substring(pubDate, 6, 2)" order="descending" data-type="number"/>
            <!-- hour -->
            <xsl:sort select="substring(pubDate, 18, 2)" order="descending" data-type="number"/>
    
            </xsl:apply-templates>
            <xsl:apply-templates select="@*|node()[not(following-sibling::item) and not(self::item)]"/>
    </xsl:copy>
    </xsl:template>