如何在xquery中计算一个父元素的子元素数量

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

我是 xquery 的新手,我正在尝试计算每个音乐家拥有的专辑数量。

我的数据如下:

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

预期输出:

2
2
4

我目前的代码:

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

我的输出是

1
1
1

您目前正在计算 albums 个元素的数量,而您声明的目标是计算 album 个元素。

按如下方式更改您的代码:

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

这会产生所需的输出:

2
2
4