gpt4 book ai didi

xml - 如何使用 XSLT 检索最接近但不在特定日期之后的元素?

转载 作者:数据小太阳 更新时间:2023-10-29 02:05:13 26 4
gpt4 key购买 nike

给定一个带有日期属性的元素列表,例如,

<foo>
<bar date="2001-04-15"/>
<bar date="2002-01-01"/>
<bar date="2005-07-04"/>
<bar date="2010-11-10"/>
</foo>

我想使用 XSLT 检索最接近但不在给定日期之后的元素。

用参数“2008-01-01”调用这个函数应该打印<bar date="2005-07-04"> .假设上下文节点已经是 <foo> .

我不确定哪个更容易,但我还可以设置三个属性:日、月、年,而不是只有一个日期属性。

最佳答案

对于 XSLT 1.0 这很棘手,因为它不支持将日期作为第一类值,也不支持字符串的字典顺序比较。而且它(根据规范)不支持在临时变量中构建节点集,然后从该集合中提取单个节点。尽管如此,您可以通过一些技巧实现您想要的效果。

您的日期为 YYYY-MM-DD 的事实意味着,如果您去掉连字符并将结果字符串视为数字,则按数字顺序对这些数字进行排序会得到与按时间顺序对原始日期进行排序相同的结果命令。尽管 XSLT 没有可更新的变量,但您可以通过使用一个模板来获得类似的效果,该模板将自身逐个递归地应用于同级节点,并在模板参数中向下传递状态。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:param name="targetDate" select="20080101" />

<xsl:template match="foo">
<!-- find the first "candidate" bar whose date is before the target date -->
<xsl:apply-templates select="(bar[translate(@date, '-', '') &lt; $targetDate])[1]" />
</xsl:template>

<xsl:template match="bar">
<xsl:param name="closest" select="." />
<!-- find the next candidate bar whose date is before the target date -->
<xsl:variable name="nextCandidate"
select="(following-sibling::bar[translate(@date, '-', '') &lt; $targetDate])[1]" />
<xsl:choose>
<xsl:when test="$nextCandidate">
<xsl:choose>
<xsl:when test="translate($nextCandidate/@date, '-', '') &gt; translate($closest/@date, '-', '')">
<!-- $nextCandidate is closer to the target than the current $closest -->
<xsl:apply-templates select="$nextCandidate">
<xsl:with-param name="closest" select="$nextCandidate" />
</xsl:apply-templates>
</xsl:when>
<xsl:otherwise>
<!-- current $closest is still the closest -->
<xsl:apply-templates select="$nextCandidate">
<xsl:with-param name="closest" select="$closest" />
</xsl:apply-templates>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:otherwise>
<!-- no more candidates, so $closest is the node we require -->
<xsl:copy-of select="$closest" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>


</xsl:stylesheet>

关于xml - 如何使用 XSLT 检索最接近但不在特定日期之后的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13769874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com