artfulrobot
artfulrobot

Reputation: 21437

Xpath get node that only contains nodes of a certain type

Take this (id attributes only added so I can refer to them below)

<div id="one">
   <figure>foo</figure>
   <figure>bar</figure>
</div>
<div id="two">
   <figure>foo</figure>
   <div>bar</div>
</div>
<div id="three">
   <div>bar</div>
</div>

How can I select all div elements whose children are all figure elements, i.e. selecting div one only in the given example?

I sort of need //div[count(not figure)>0].

Upvotes: 0

Views: 310

Answers (2)

artfulrobot
artfulrobot

Reputation: 21437

I did it like this:

//div[figure][count(figure) = count(*)]

This finds divs that must contain at least one figure, and then it checks that the count of figure elements matches the count of all other elements; if this is true then it cannot contain anything else.

Upvotes: 0

har07
har07

Reputation: 89325

This is one possible way :

//div[not(*[name() != 'figure']) and not(text()[normalize-space()])]

The left-side of and make sure the div doesn't have child element named other than 'figure', and the right-side make sure it doesn't have non-empty child text node.

or, the same approach but using count() :

//div[count(*[name() != 'figure']|text()[normalize-space()]) = 0]

Upvotes: 1

Related Questions