gpt4 book ai didi

xslt - 在 XPath 2.0 中表达集合相等的惯用方式

转载 作者:行者123 更新时间:2023-12-04 12:20:06 26 4
gpt4 key购买 nike

如果 $A 和 $B 是序列,那么测试 $A 和 $B 的集合相等性的惯用首选方法是什么?我知道 ($A = $B) 的存在语义行为使这个表达不是答案。 deep-equal() 的排序语义也禁止我使用它。

我的冲动是使用:

((every $a in $A satisfies $a = $B) and (every $b in $B satisfies $b = $A))

我发现通过 Google 进行的集合相等性测试很少(准确地说,我完全没有发现),而且我在 @Michael-Kay 中没有看到它提到。的第 8、9、10 或 13 章。很难相信我是第一个遇到这种需求的 XPath 用户。这让我怀疑我是否问错了问题。

最佳答案

一个有趣且问得很好的问题!在我看来,使用 everysatisfies克服序列比较的存在特性是一种非常有效且足够规范的方法。

但是既然你问的是另一种方法:如何在与 deep-equal() 比较之前对序列进行排序? ?让我们假设以下样式表中有两个序列:

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

<xsl:variable name="A" select="('a','b','c')"/>
<xsl:variable name="B" select="('a','c','b')"/>

<xsl:template match="/">
<xsl:choose>
<xsl:when test="deep-equal($A,$B)">
<xsl:text>DEEP-EQUAL!</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>NOT DEEP-EQUAL</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

</xsl:transform>

当然,这个转换返回
NOT DEEP-EQUAL

但是,如果您在比较之前对序列进行排序,例如使用使用 xsl:perform-sort 的自定义函数,见 relevant part of the specification :
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
xmlns:local="www.local.com" extension-element-prefixes="local"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output method="text"/>

<xsl:variable name="A" select="('a','b','c')"/>
<xsl:variable name="B" select="('a','c','b')"/>

<xsl:template match="/">
<xsl:choose>
<xsl:when test="deep-equal(local:sort($A),local:sort($B))">
<xsl:text>DEEP-EQUAL!</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>NOT DEEP-EQUAL</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

<xsl:function name="local:sort" as="xs:anyAtomicType*">
<xsl:param name="in" as="xs:anyAtomicType*"/>
<xsl:perform-sort select="$in">
<xsl:sort select="."/>
</xsl:perform-sort>
</xsl:function>

</xsl:transform>

那么,结果将是
DEEP-EQUAL!

编辑 : 其实 设置相等将意味着不仅顺序无关紧要,而且重复也不应该有所作为。因此,适当的集合相等意味着也适用 distinct-values()到序列变量:
<xsl:when test="deep-equal(local:sort(distinct-values($A)),local:sort(distinct-values($B)))">

关于xslt - 在 XPath 2.0 中表达集合相等的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29266152/

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