Home > OS >  How to count the number of clild elements with one parent in xquery
How to count the number of clild elements with one parent in xquery

Time:10-27

Im new to xquery and im trying to count the number of albums that each musician has.

My data is as follows:

<musicians>
    <musician type="band">
        <name>If These Trees Could Talk</name>
        <genre>Post-Rock</genre>
        <albums>
            <album year="2006">If These Trees Could Talk</album>
            <album year="2009">Above the Earth, Below the Sky</album>
        </albums>
    </musician>
    <musician type="solo">
        <name>Justin Bergh</name>
        <genre>Pop-Rock</genre>
        <albums>
            <album year="2005">Out of My Hands</album>
            <album year="2010">Lateralus</album>
        </albums>
    </musician>
    <musician type="band">
        <name>Tool</name>
        <genre>Progressive Metal</genre>
        <albums>
            <album year="1993">Undertow</album>
            <album year="1996">Aenima</album>
            <album year="2001">Lateralus</album>
            <album year="2006">10,000 Days</album>
        </albums>
    </musician>
</musicians>

The expected output:

2
2
4

My code currently:

for $n in //musicians/musician/albums
let $count := count($n)
return $count

My output is

1
1
1

CodePudding user response:

You're currently counting the number of albums elements, while you're stated goal is to count the album elements.

Change your code as follows:

for $n in //musicians/musician/albums
let $count := count($n/album)
return $count

This yields the required output:

2
2
4
  • Related