如何在 XPath 1.0 中执行集合操作 [英] How to perform set operations in XPath 1.0
问题描述
我在 SO 和其他地方看到以下内容应该可以工作(这个例子直接取自 O'Reilly 的 XSLT Cookbook):
I've seen on SO and other places that the following is supposed to work (this example is lifted directly from O'Reilly's XSLT Cookbook):
(: intersection :)
$set1[count(. | $set2) = count($set2)]
(: difference :)
$set1[count(. | $set2) != count($set2)]
看起来应该没问题,但是当与实际路径而不是变量一起使用时,这似乎失败了.例如,给定以下文档
and it looks like it should be OK, however this seems to fail when used with actual paths rather than variables. For example, given the following document
<a>
<new>
<val>1</val>
<val>2</val>
</new>
<old>
<val>2</val>
<val>3</val>
</old>
</a>
和 XPath 表达式 /a/new/val[count(. |/a/old/val)=count(/a/old/val)]/text()
我期望获取节点集 { 2 }
而是获取 { 1 2 }
.知道我做错了什么吗?
and the XPath expression /a/new/val[count(. | /a/old/val)=count(/a/old/val)]/text()
I would expect to get the node-set { 2 }
but instead am getting { 1 2 }
. Any ideas what I'm doing wrong?
推荐答案
节点集交集的公式使用节点标识,而不是值标识.
The formulas for node-set intersection use node-identity, not value identity.
两个节点相同当且仅当 count($n1|$n2) =1
Two nodes are identical if and only if count($n1|$n2) =1
但是,您希望基于值标识相交.
However, you want to intersect based on value identity.
解决方案:
使用:
/a/new/val[. = /a/old/val]
这将选择任何 /a/new/val
至少存在一个 /a/old/val
元素,使得这两个元素的字符串值是一样.
this selects any /a/new/val
for which there exists at least one /a/old/val
element such that the string values of these two elements is the same.
这篇关于如何在 XPath 1.0 中执行集合操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!