tags:

views:

153

answers:

5

I have this kind of node in my xml document:

<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?

Parent can have also other children.

+2  A: 
<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:

element[a][b]

...I think.

ScottSEA
+1  A: 

Something like this should do it: //[a and b]

Michael Donohue
Do you want to search for parent nodes named 'parent' specifically or find any node with an 'a' and 'b' child element?
Michael Donohue
A: 
 //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.

Brian Agnew
that would have to be parent::*[count(a) > 0 and count (b) >0], wouldn't it?
ScottSEA
@Brian Agnew: no, you're right - I was confusing an element named "parent" and the parent:: xpath axis. Mea Culpa.
ScottSEA
That's good :-) Thx for the feedback
Brian Agnew
+1  A: 
//*[child::a and child::b]
bruno conde
+1  A: 

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.

Tomalak