cosmos7263
cosmos7263

Reputation: 43

XPath to select elements with no children?

<div>
<p> text 1 </p> 
<p>
    <a href="http://www.google.com">text 2</a>
</p> 
<p> text 3  </p> 
<p> text 4 </p> 
</div>

I used this: //p but this also gives me the <p> where text 2 is. I want <p>s without children. I need: text 1, text 3, text 4

Upvotes: 4

Views: 1929

Answers (1)

kjhughes
kjhughes

Reputation: 111726

Here are XPaths for various interpretations of no children...

  • No element children:

    //p[not(*)]
    
  • No text children:

    //p[not(text())]
    
  • No children of any type:

    //p[not(node())]
    

Replace p above with any other element name, or * to target elements regardless of name.

Upvotes: 8

Related Questions