【问题标题】:XSLT - get node closest to current timestampXSLT - 获取最接近当前时间戳的节点
【发布时间】:2014-04-01 06:44:20
【问题描述】:

我有一组带有时间戳格式的日期的节点,我正在使用<xsl:for-each> 对其进行迭代。如何获取最接近保存在$currentDate 中的当前日期的节点?

 <xsl:variable name="currentDate" select="1396332574" />

 <items>
   <item>
      <tmstmp>1374249600</tmstmp>
   </item>
   <item>
      <tmstmp>1374249600</tmstmp>
   </item>
   <item>
      <tmstmp>1374257700</tmstmp>
   </item>
   <item>
      <tmstmp>1374418800</tmstmp>
   </item>
   <item>
      <tmstmp>2777068800</tmstmp>
   </item>
 </items>

【问题讨论】:

  • 从上面的tmstmp,你期望的输出是什么?
  • 编辑:添加节点以进行澄清...

标签: xml xslt xml-parsing xslt-1.0


【解决方案1】:

试试

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:strip-space elements="*"/>

    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:variable name="currentDate" select="1396332574" />

    <xsl:template match="/">
        <xsl:for-each select="items/item">
            <xsl:sort select="$currentDate - ." data-type="number" order="ascending"/>
            <xsl:if test="position() = 1">
                <xsl:copy-of select="."/>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

它输出:

<item>
   <tmstmp>1374418800</tmstmp>
</item>

【讨论】:

  • 谢谢,但这不起作用,因为最远的日期总是在最前面。我需要最近的日期(在您的代码中最接近零)。我猜想通过 abs 值对其进行排序是可行的。
  • 请看这个 (xsltransform.net/bFukv8o)。它输出我在上面发布的内容。 1374418800 是否最接近 1396332574
  • 您可以在xsl:sortselect 属性上使用xpath 表达式,就像我在上面所做的那样。
  • xsltransform.net/bFukv8o/5 当前日期是 2014 年 4 月 1 日。最后一个节点是 2058 年 1 月 1 日,这不是最接近当前日期的日期。 +1 为我指明方向
  • ($currentDate - ./tmstmp)*(($currentDate - ./tmstmp) >=0) - ($currentDate - ./tmstmp)*(($currentDate - ./tmstmp) &lt ; 0) 成功了
猜你喜欢
  • 2016-05-31
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2011-12-26
  • 2012-03-04
相关资源
最近更新 更多