使用XSL按照RFC-822日期格式对XML进行排序

问题描述:

有人知道在XSL中做这种排序的方法吗?使用XSL按照RFC-822日期格式对XML进行排序

这是我到目前为止,但它只是按日排序,忽略了日期的其余部分。

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

的日期只是日期或日期时间?你在使用XSLT 1.0还是XSLT 2.0?你也可以编辑你的答案张贴你的XML? – 2013-02-21 22:08:17

+1

这当然是可能的,但不是微不足道的。您必须在XSLT中编写一个解析器,将RFC-822日期转换为可排序的日期。我会使用EXSLT函数和XPath字符串函数。 – nwellnhof 2013-02-21 23:33:06

+1

这可能会有所帮助http://www.codeproject.com/Articles/4261/Sorting-dates-in-XSL – Vinit 2013-02-22 02:04:30

感谢您的快速回复家伙。让我朝着正确的方向前进。管理解决它!找到一个有用的链接http://blog.mastykarz.nl/how-to-do-it-rss-aggregation-merging-multiple-xml-files-using-xslt/

我使用的是XSLT 2.0版。只是一个使用变量替代MMM月份并将日期细分的日子。

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> 

+1

该解决方案看起来非常脆弱,因为它假定日期时间元素始终位于字符串中的相同位置。这不一定是真的。例如,日期时间开始的星期几是可选的。此外,可能会使用一位或两位数字指定月份中的某一天。 – nwellnhof 2013-02-23 11:23:56

+1

@nwellnhof如果他们使用RFC-822日期,那不应该是这样。我假设OP正在使用RSS提要并且为了验证,pubDate有非常严格的要求。现在,pubDate并不一定是格式,但它确实是有效的。 – doubleJ 2013-11-07 19:58:01