Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath to select only nodes where child elements exist?

Tags:

xpath

This should be an easy one but it is giving me trouble. Given this structure:

<root>
  <a>
    <b/>
  </a>
  <a/>
</root>

I'm trying to formulate an xpath expression that gives only the non-empty "a" elements, i.e. the ones that have child elements. Therefore I want the first instance of "a" returned, but not the second.

So far I have "/root/a/self::*" but that is returning me both a's.

like image 342
Kevin Pauli Avatar asked Jul 17 '09 15:07

Kevin Pauli


People also ask

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 .

How do you navigate from parent to child in XPath?

Start by writing out the selenium Xpath for the parent and then traverse to desired object using back slashes like so; Xpath Parent written as //div[@class='region region-navigation' using our previously shown syntax. Now you start to traverse through the HTML nodes down to desired object.


1 Answers

/root/a[count(*)&gt;0]

will give any 'a' node with any kind of child node

like image 116
Mesh Avatar answered Sep 27 '22 22:09

Mesh