Reputation: 129
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
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'
. <sub3>
, obviously<node3>
, <sub4>
and finally <subsub>
, for the same reasonOverall 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