wizzkid
wizzkid

Reputation: 207

How can I count child nodes based on their attribute values?

I want to create a summary using XQuery 3.0 to show how many parts of each type a obj has. I have the following XML code:

<root>
    <obj>
        <name>Foo1</name>
        <stuff>
            <part type = "a"/>
            <part type = "a"/>
            <part type = "b"/>
            <part type = "d"/>
            <part type = "d"/>
        </stuff>
    </obj>
    <obj>
        <name>Foo2</name>
        <stuff>
            <part type = "a"/>
            <part type = "c"/>
            <part type = "c"/>
        </stuff>
    </obj>
    <obj>
        <name>Foo3</name>
        <stuff>
            <part type = "a"/>
            <part type = "a"/>
            <part type = "a"/>
            <part type = "b"/>
            <part type = "b"/>
            <part type = "c"/>
            <part type = "d"/>
        </stuff>
    </obj>
</root>

Furthermore I'd like the results to be displayed something like one of these ways:

        OR
Foo1    |   Foo1
a 2     |   a 2
b 1     |   b 1
d 2     |   c 0
        |   d 2
        |
Foo2    |   Foo2
a 1     |   a 1
c 2     |   b 0
        |   c 2
        |   d 0
        |
Foo3    |   Foo3
a 3     |   a 3
b 2     |   b 2
c 1     |   c 1
d 1     |   d 1
        |

Upvotes: 0

Views: 72

Answers (1)

Ewout Graswinckel
Ewout Graswinckel

Reputation: 1273

group by should work nicely here:

for $obj in //obj
return 
  <result>
    {$obj/name}
    {
    for $part in $obj//part
          group by $type := $part/@type 
          return <part type="{$type}">{count($part)}</part>
    }
  </result>

Upvotes: 2

Related Questions