I have this kind of node in my xml document:
我的xml文档中有这种节点:
<parent ...>
<a .../>
<b .../>
</parent>
Parent node can have both a and b, only a, only b, or none of them. I want to write a XPath to get all parents that have both. Can I do that?
父节点可以同时具有a和b,仅具有a,仅具有b或不具有b。我想写一个XPath来让所有拥有这两者的父母。我能这样做吗?
Parent can have also other children.
父母也可以有其他孩子。
5 个解决方案
#1
<element>
<a/>
<b/>
</element>
element[child::a][child::b]
this should select all the elements with a and b as direct children, regardless if they have additional children or not. Or, more simply:
这应该选择a和b作为直接孩子的所有元素,无论他们是否有额外的孩子。或者,更简单:
element[a][b]
...I think.
#2
Something like this should do it: //[a and b]
这样的事情应该这样做:// [a和b]
#3
//*[child::a and child::b]
#4
Obvious:
parent[a and b]
The child axis is implicit in predicates, this means there is no need to mention it.
子轴隐含在谓词中,这意味着无需提及它。
parent[child::a and child::b] <!-- the same, only longer -->
The use of two separate predicates is possible as long as the conditions are conjunctive ("and"):
只要条件是连接的(“和”),就可以使用两个单独的谓词:
parent[a][b] <!-- the same, slightly shorter -->
This saves three characters in expression length. However, the use of two predicates triggers two separate checks, since they are applied one after another. Using one predicate with a boolean operator seems to be the simplest and cleanest approach to me.
这样可以在表达式中保存三个字符。但是,使用两个谓词会触发两个单独的检查,因为它们是一个接一个地应用的。使用一个带有布尔运算符的谓词似乎是对我来说最简单,最干净的方法。
#5
//parent[count(a) > 0 and count(b) > 0]
should do it. There's a great XPath testbed here that makes life very easy, in terms of highlight the matched nodes etc.
应该这样做。这里有一个很棒的XPath测试平台,在突出匹配节点等方面让生活变得非常简单。
#1
<element>
<a/>
<b/>
</element>
element[child::a][child::b]
this should select all the elements with a and b as direct children, regardless if they have additional children or not. Or, more simply:
这应该选择a和b作为直接孩子的所有元素,无论他们是否有额外的孩子。或者,更简单:
element[a][b]
...I think.
#2
Something like this should do it: //[a and b]
这样的事情应该这样做:// [a和b]
#3
//*[child::a and child::b]
#4
Obvious:
parent[a and b]
The child axis is implicit in predicates, this means there is no need to mention it.
子轴隐含在谓词中,这意味着无需提及它。
parent[child::a and child::b] <!-- the same, only longer -->
The use of two separate predicates is possible as long as the conditions are conjunctive ("and"):
只要条件是连接的(“和”),就可以使用两个单独的谓词:
parent[a][b] <!-- the same, slightly shorter -->
This saves three characters in expression length. However, the use of two predicates triggers two separate checks, since they are applied one after another. Using one predicate with a boolean operator seems to be the simplest and cleanest approach to me.
这样可以在表达式中保存三个字符。但是,使用两个谓词会触发两个单独的检查,因为它们是一个接一个地应用的。使用一个带有布尔运算符的谓词似乎是对我来说最简单,最干净的方法。
#5
//parent[count(a) > 0 and count(b) > 0]
should do it. There's a great XPath testbed here that makes life very easy, in terms of highlight the matched nodes etc.
应该这样做。这里有一个很棒的XPath测试平台,在突出匹配节点等方面让生活变得非常简单。