Peter
Peter

Reputation: 19

count element using Xquery and return both the element name and value

I have to count how many times of the authors show in a XML file. Lets say,as attached - XML

Frank Manola has appeared 2 times and Tolga Yurek has appeared 1 time.

My desire result is:

Frank Manola , 2
Tolga Yurek, 1

I used this code, but I cannot archive it:

for $a in doc("dblp.xml")/dblp/* let$c := count ($a/author) return ($a/author , $c)

Result become very weird like this:unwanted result

What error in my code? What can I group and sum them up?

Upvotes: 0

Views: 86

Answers (2)

Wallarou
Wallarou

Reputation: 63

You are iterating several times on the same author. Maybe you should use distinct-values when you loop on the authors?

Something like:

for $a in distinct-values(doc("file.xml")//author)
  let $c := count(//author[. = $a])
  return ($a, $c)

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167716

In XQuery 3 you can use group by https://www.w3.org/TR/xquery-31/#id-group-by:

for $author in doc("dblp.xml")/dblp/*/author
group by $a := $author
return $a || ': ' || count($author)

https://xqueryfiddle.liberty-development.net/b4GWVe/1

Upvotes: 1

Related Questions