Getodac
Getodac

Reputation: 129

Xpath count non-empty descendants

Well, I have the next xml input:

<root>
  <node1>
    <sub1/>
    <sub2/>
    <sub3>sub3</sub3>
  </node1>
  <node2/>
  <node3>
    <sub4>
      <subsub>text</subsub>
    </sub4>
  </node3>
</root>

How can I count non-empty text descendants of root element (sub3, text)? When I use count(/root/descendant::*[normalize-space()]) it counts 5, but I expect to be 2. I tried to count the non-empty text descendants for element like that:

count(/root/node3/descendant::*[text()])

and it returns 2, but i expect to be 1.

Where I'm wrong?

Upvotes: 2

Views: 2554

Answers (1)

Tomalak
Tomalak

Reputation: 338118

I think you want

count(//*[not(*) and normalize-space()])

i.e., those that themselves don't have child elements but do have some text.


If you want to count actual, physical text nodes, that would be

count(//*[not(*)]/text())

With your input that results in two text nodes being selected, but it would also count empty (whitespace-only) text nodes if they were there.


Your error is that /root/descendant::*[normalize-space()] selects

  • <node1> as non-empty because it (indirectly) contains the string 'sub3'.
  • then it selects <sub3>, obviously
  • then it selects <node3>, <sub4> and finally <subsub>, for the same reason

Overall this is five nodes.

/root/node3/descendant::*[text()] selects <sub4>, because there are text children (albeit whitespace-only ones) and <subsub>, of course. That's two nodes.

Upvotes: 2

Related Questions