2

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>

2 Answers 2

4
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

Sign up to request clarification or add additional context in comments.

3 Comments

Looks good, except I'd recommend . or string(.) instead of text(). text() can cause things to break if <type> contains any markup. Even if you know it never will, there's no good reason I can think of to use text() instead of the node's string-value. text() is usually a code smell in XQuery.
ya ya, good point though the op was specifically working on text() hence the choice of text() ... you following me on the internets ?
Yes, insofar as you are synonymous with "xquery" (which I suppose is the case on Twitter) :-)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.