Home > OS >  XPath to select elements with no children?
XPath to select elements with no children?

Time:10-22

<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

CodePudding user response:

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.

CodePudding user response:

Try using

//p[count(.//*)=0]

instead on your actual xml and see if it works. The expression selects only elements which have zero children.

EDIT:

or... you can use the expression in kjhughes' comment...

  • Related