如何根据属性值计算子节点?

时间:2014-08-28 15:14:55

标签: xml xquery xquery-3.0 flwor

我想使用XQuery 3.0创建一个摘要,以显示obj具有的每种类型的部分。我有以下XML代码:

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

此外,我希望结果显示为以下方式之一:

        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
        |

1 个答案:

答案 0 :(得分:2)

group by应该在这里工作得很好:

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>