Reputation: 299
I'm trying to count the number of nodes that contain a certain word. How can I count the number of total matches?
<Fruit>
<type>apple</type>
<type>orange</type>
<type>apple</type>
<type>apple</type>
</Fruit>
So the count for apple is 3. How do I get it. I've been able to get the information, and after normalizing I can print out:
<text>apple orange apple apple</text>
Upvotes: 2
Views: 6752
Reputation: 4126
To count elements having an exact value, use eq
:
count(/Fruit/type[. eq 'apple'])
To count elements containing a particular substring, use contains()
:
count(/Fruit/type[contains(.,'apple')])
So that would also include <type>this is an apple</type>
.
For general word search, you need something beyond XQuery 1.0. For example, if you're using MarkLogic, you can do:
count(/Fruit/type[cts:contains(.,'apple')])
which will also match things like <type>Apples</type>
.
Upvotes: 1
Reputation: 362
let $a := <Fruit>
<type>apple</type>
<type>orange</type>
<type>apple</type>
<type>apple</type>
</Fruit>
return
count($a/type[text() eq 'apple'])
should get you there
Upvotes: 4