Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can XPath return only nodes that have a child of X?

Tags:

xml

xslt

xpath

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'.

like image 862
Ryan Stille Avatar asked Sep 19 '08 21:09

Ryan Stille


People also ask

How do you specify a child element using XPath?

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.

What is child :: In XPath?

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.

How do I select the first child in XPath?

The key part of this XPath is *[1] , which will select the node value of the first child of Department .

Which kinds of nodes are available in XPath?

In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document nodes.


1 Answers

Here it is, in all its glory

/pets/*[bar] 

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

like image 128
Chris Marasti-Georg Avatar answered Sep 19 '22 15:09

Chris Marasti-Georg