格式化日期比较日期XSLT

时间:2013-05-24 13:40:50

标签: date xslt format compare

我有一个XML文件,其中包含有关以下事件的说明和日期:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="timedate.xsl"?>
<catalog>
    <event>
        <name>AAA Festival</name>
        <place>New York</place>
        <country>USA</country>
        <date>19/11/2013</date>
    </event>
    <event>
        <name>BBB Festival</name>
        <place>Paris</place>
        <country>France</country>
        <date>11/10/2013</date>
    </event>
    <event>
        <name>CCC Festival</name>
        <place>London</place>
        <country>UK</country>
        <date>29/09/2013</date>
    </event>
</catalog>

和一个XSL文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>

<xsl:template match="/">
<html>
  <body>
    <h2>Upcoming events</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Name</th>
        <th>Place</th>
        <th>Country</th>
        <th>Date</th> 
      </tr>
      <xsl:for-each select="catalog/event">
      <xsl:sort select="date" order="descending"/>
      <tr>
        <td><xsl:value-of select="name"/></td>
        <td><xsl:value-of select="place"/></td>
        <td><xsl:value-of select="country"/></td>
        <td><xsl:value-of select="date"/></td>
</tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>

我想创建一个页面,只排序和列出即将发生的事件(包括今天的日期)。我无法做到这一点,因为日期格式不正确,我可以获得当前日期来比较它们并打印未来事件。请通过一个有效的示例告诉我解决方案。在此先感谢您的回复和帮助。问候!

1 个答案:

答案 0 :(得分:0)

想要比较/排序与将原始日期转换为数字格式有关的日期。例如,通过公式year*372+12*month*31+day(372和31是好的,因为你真的不需要精确的数字)

如果您的xml具有固定的日期格式(例如,您确定1始终为01),则可以使用XPath函数substring

已编辑 - 关于您的申请,我正在提供xsl的完整样本。

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>

<xsl:template match="/">
<html>
  <body>
    <h2>Upcoming events</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Name</th>
        <th>Place</th>
        <th>Country</th>
        <th>Date</th> 
      </tr>
      <xsl:for-each select="catalog/event">
        <xsl:sort 
         select="number(substring(date, 7, 4))*372+12*31*number(substring(date, 4, 2))+number(substring(date, 1, 2))" 
         order="descending" data-type="number"/>
        <tr>
            <td><xsl:value-of select="name"/></td>
            <td><xsl:value-of select="place"/></td>
            <td><xsl:value-of select="country"/></td>
            <td><xsl:value-of select="date"/></td>
            <!-- column just for debug-->
            <td><xsl:value-of select="number(substring(date, 7, 4))*372+12*31*number(substring(date, 4, 2))+number(substring(date, 1, 2))"/></td>
        </tr>
      </xsl:for-each>

    </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>
相关问题