tags:

views:

823

answers:

4

Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the lizard and pig elements.

<pets>
<cat>
  <foo>don't care about this</foo>
</cat>
<dog>
   <foo>not this one either</foo>
</dog>
<lizard>
   <bar>lizard should be returned, because it has a child of bar</bar>
</lizard>
<pig>
   <bar>return pig, too</bar>
</pig>
</pets>

This Xpath gives me all pets: "/pets/*", but I only want the pets that have a child node of 'bar'.

+8  A: 

Here it is, in all its glory

/pets/*[bar]

English: Give me all children of pets that have a child bar

Chris Marasti-Georg
That works great, thank you.
+2  A: 

Don't underestimate the w3c specs in terms of readability and usefulness. It is probably faster to look the answers to questions like these in the spec, which is very readable and complete, with many examples.

Confusion
A: 

Just out of interest, what's the correct syntax to do that using the "child::" axis method?

AmbroseChapel
/child::pets/child::*[child::bar]
Eric Weilnau
A: 

/pets/child::*[child::bar]

My pardon, I did not see the comments to the previous reply.

But in this case I'd rather prefer using the descendant:: axis, which includes all elements down from specified.

/pets[descendant::bar]