Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count with condition in xquery

I have a node with a child node, that has a content like this:

<parent>
  <child>a</child>
  <child>b</child>
  <child>c</child>
  <child>a</child>
  <child>c</child>
</parent>

I want to count the number of childs that have an 'a' as content.

So far I've tried:

count($node/child/'a')

But that gives me only the number of all childs. What is the proper way to do this?

like image 726
Sharivari Avatar asked Nov 29 '25 15:11

Sharivari


1 Answers

Try this:

let $parent :=
  <parent>
    <child>a</child>
    <child>b</child>
    <child>c</child>
    <child>a</child>
    <child>c</child>
  </parent>
return count($parent/child[text() = 'a'])

It would also count <child>a<foobar/>b</child>, since the text node a is found. To compare all text contexts, you can use $parent/child[. = 'a'].

like image 106
Leo Wörteler Avatar answered Dec 01 '25 06:12

Leo Wörteler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!