XPath 2.0 中有布尔值 any-function 吗?
Is there a boolean any-function in XPath 2.0?
假设我有以下 XML
<root>
<a>
<b>hi</b>
<b>ho</b>
</a>
<a>
<b>foo</b>
<b>barnacle</b>
<b>baz</b>
</a>
<a>
<b>bye</b>
</a>
</root>
我想编写一个 XPath 2.0 表达式来匹配 a
元素,该元素具有任何以文本 bar
开头的 b
child,无论哪个 b
child 是多少 b
children.
我在想这看起来像
/root/a[starts-with(string(b), 'bar')]
但 starts-with
将字符串作为输入,而不是序列。所以也许像
/root/a[any(for $b in b return starts-with(string($b), 'bar'))]
但我在 XPath 2.0 中找不到 any
函数。如果它存在,我会期望它采用一系列布尔值并返回 true
如果序列中的任何元素是 true
.
我可以用整数模拟 any
函数 "faking" 布尔逻辑
/root/a[sum(for $b in b return if starts-with(string($b), 'bar') then 1 else 0) > 0]
但这是一个 hacky 和 difficult-to-read 解决方案。我更喜欢更好的方法。
我错过了什么吗?有更好的方法吗?
事实证明,在我写这个问题时,我寻找的 any
函数存在,只是名称不同:some
。从技术上讲,这不是函数,而是具有特殊语法的自己的 XPath 表达式。
我应该会写
/root/a[some $b in b satisfies starts-with(string($b), 'bar')]
得到我想要的结果。
假设我有以下 XML
<root>
<a>
<b>hi</b>
<b>ho</b>
</a>
<a>
<b>foo</b>
<b>barnacle</b>
<b>baz</b>
</a>
<a>
<b>bye</b>
</a>
</root>
我想编写一个 XPath 2.0 表达式来匹配 a
元素,该元素具有任何以文本 bar
开头的 b
child,无论哪个 b
child 是多少 b
children.
我在想这看起来像
/root/a[starts-with(string(b), 'bar')]
但 starts-with
将字符串作为输入,而不是序列。所以也许像
/root/a[any(for $b in b return starts-with(string($b), 'bar'))]
但我在 XPath 2.0 中找不到 any
函数。如果它存在,我会期望它采用一系列布尔值并返回 true
如果序列中的任何元素是 true
.
我可以用整数模拟 any
函数 "faking" 布尔逻辑
/root/a[sum(for $b in b return if starts-with(string($b), 'bar') then 1 else 0) > 0]
但这是一个 hacky 和 difficult-to-read 解决方案。我更喜欢更好的方法。
我错过了什么吗?有更好的方法吗?
事实证明,在我写这个问题时,我寻找的 any
函数存在,只是名称不同:some
。从技术上讲,这不是函数,而是具有特殊语法的自己的 XPath 表达式。
我应该会写
/root/a[some $b in b satisfies starts-with(string($b), 'bar')]
得到我想要的结果。