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 from this example:
<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 name 'bar'
.
For the div element with an id attribute of hero //div[@id='hero'] , these XPath expression will select elements as follows: //div[@id='hero']/* will select all of its children elements. //div[@id='hero']/img will select all of its children img elements. //div[@id='hero']//* will select all of its descendent elements.
As defined in the W3 XPath 1.0 Spec, " child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.
The key part of this XPath is *[1] , which will select the node value of the first child of Department .
In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document nodes.
Here it is, in all its glory
/pets/*[bar]
English: Give me all children of pets
that have a child bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With