Sharivari
Sharivari

Reputation: 103

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?

Upvotes: 3

Views: 1082

Answers (1)

Leo W&#246;rteler
Leo W&#246;rteler

Reputation: 4241

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'].

Upvotes: 3

Related Questions