【问题标题】:XSL - Get attribute of previous elementXSL - 获取前一个元素的属性
【发布时间】:2011-03-04 11:40:03
【问题描述】:

在下面的if 块中,我还想测试@Timestamp 是否小于之前的Message 的时间戳。我怎样才能做到这一点?

<xsl:for-each select="Message">
    <xsl:sort select="position()" data-type="number" order="descending"/>
    <xsl:variable name="newclass">
        <xsl:if test="@Timestamp + 60 &gt; $ctimestamp">new</xsl:if>
    </xsl:variable>

    <tr><td class="debugtime">
        <xsl:value-of select="@Time"/>
    </td><td class="{$newclass}">
        <xsl:value-of select="node()"/>
    </td></tr>
</xsl:for-each>

示例 XML

<Message Time="2010/06/17 04:23:32" Timestamp="1276773812">message1</Message>
<Message Time="2010/06/17 04:23:32" Timestamp="1276773812">message2</Message>
<Message Time="2010/06/17 04:23:33" Timestamp="1276773813">message3</Message>
<Message Time="2010/06/17 04:23:33" Timestamp="1276773813">message4</Message>

更新: 我已经实现了当前答案的两种变体,但没有运气。从第二个元素开始,它似乎总是不能正常工作,因为它会正确地加粗第一个但不会再加粗(尽管有时它会做第三个)。更新了下面的 if 块代码。

<xsl:if test="@Timestamp + 60 &gt; $ctimestamp">
    <xsl:if test="position() = 1">
        new
    </xsl:if>
    <xsl:if test="position() != 1 and ../Message[position()-1]/@Timestamp - 1 &lt; @Timestamp">
        new
    </xsl:if>
</xsl:if>

【问题讨论】:

  • @Chris:请发布一些 XML 输入文档。
  • 如果您向我的代码块提供您提供的示例 xml,那么这就是所需的行为,输出第一和第三。看看时间戳的变化。另外,$ctimestamp 的值是多少?
  • 请原谅,我想要 &lt;= 行为并添加了一个 -1(如上面新更新的代码中所反映的那样),但在进行初始更新时错过了它。
  • 您似乎无法解释您想要什么。您的代码中的“-1”应该做什么?在 XML 片段中,有一个 no 节点,其时间戳小于之前的任何节点!你在说什么???
  • 在示例 XML 中有 4 个节点,2 个节点的时间戳为 1276773812,另外两个节点的时间戳为 1276773813(一秒后)。 -1 是因为我不确定如何在 XSL 中执行 &lt;=,所以我通过取掉 1 来模拟效果。

标签: xml xslt xpath


【解决方案1】:
@Timestamp &lt; preceding-sibling::Message[1]/@Timestamp

【讨论】:

  • 忘记了 XPath 轴,但也许应该是 @Timestamp < previous-sibling::Message[position()+1]/@Timestamp 取决于 XPath 选择给我们的内容。
  • 请查看我的更新,我尝试了您的实现以及我更新代码中当前列出的实现。我还尝试了@Meiscooldude 的变体
  • 谢谢 Max - 这似乎每隔一行交替加粗,即 1,3,5,7 等
  • 啊...让它与following-sibling 一起工作,而不是preceeding-sibling - 谢谢
  • @Chris:我不明白,我以为你想和上一条消息比较,你为什么用following-sibling
【解决方案2】:

我还没有测试过这个解决方案,但你应该这样做。

<xsl:for-each select="Message">
    <xsl:sort select="position()" data-type="number" order="descending"/>

    <xsl:variable name="newclass">
      <xsl:if test="position() != 1">
         <xsl:if test="..\Message[position()-1]@Timestamp &lt; @Timestamp">new</xsl:if>
      </xsl:if>
      <xsl:if test="position() = 1">
         new
      </xsl:if>
    </xsl:variable>

   <tr><td class="debugtime">
       <xsl:value-of select="@Time"/>
   </td><td class="{$newclass}">
       <xsl:value-of select="node()"/>
   </td></tr>

</xsl:for-each>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多