开发者

Find element all of whose children have a given value

开发者 https://www.devze.com 2023-01-03 16:31 出处:网络
for example, i have this xml <elements> <a> <b>6</b> <b>5</b> <b>6</b>

for example, i have this xml

<elements>
<a>
     <b>6</b> 
     <b>5</b>
     <b>6</b>
</a>
<a>
     <b>5</b>
     <b>5</b>
     <b>6</b>
</a>
<a>
     <b>5</b>
     <b>5</b>
     <b>5</b>
     <b>5</b>
</a>
</elements>

i need a xpath query, which must return me parent tag, only if all its children are equal to 5 (a[3] in this case). Something like 开发者_开发问答that

//b[text()="5"]/..

but with check of all children's tags. Please note that number of children tags can be different from node to node.

It's possible with only xpath query?

thanks


/elements/a[count(b) = count(b[.="5"])]


Instead of looking for elements where all <b/> equal 5, you can look for elements that do not have any <b/> not equal 5. It is semantically the same thing but it's more performant because you don't have to consider all the children, if any of them are not "5" the XPath engine can bail early without evaluating the rest.

In other words, "all b are 5" is the same as "there is no b that isn't 5."

/elements/a[not(b != "5")]

Note that both expressions are true if there is no <b/> at all, you'd have to add another predicate for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消