XQuery如何使用唯一标识符从相似的XML结构中添加值

时间:2018-08-25 12:34:48

标签: xml xml-parsing xquery

我有类似的XML结构,例如。

<PLAYERS>
    <PLAYER>
        <NAME>Jack</NAME>
        <SCORE>120</SCORE>
    </PLAYER>
    <PLAYER>
        <NAME>Joe</NAME>
        <SCORE>100</SCORE>
    </PLAYER>
    <PLAYER>
        <NAME>Jane</NAME>
        <SCORE>170</SCORE>
    </PLAYER>
</PLAYERS>

<PLAYER>
    <NAME>Joe</NAME>
    <SCORE>40</SCORE>
</PLAYER>
<PLAYER>
    <NAME>Jane</NAME>
    <SCORE>20</SCORE>
</PLAYER>

我想获得第一个数据结构,但分数要与匹配元素NAME相加。对于此示例,将为:

<PLAYERS>
    <PLAYER>
        <NAME>Jack</NAME>
        <SCORE>120</SCORE>
    </PLAYER>
    <PLAYER>
        <NAME>Joe</NAME>
        <SCORE>140</SCORE>
    </PLAYER>
    <PLAYER>
        <NAME>Jane</NAME>
        <SCORE>190</SCORE>
    </PLAYER>
</PLAYERS>

如您所见,第二个数据集中不存在的每个名称仍应显示在最终结果中。我提出了一些想法,但是XQuery中使用的FLOWR表达式对我来说有点令人困惑。考虑过使用两个for循环。

有解决方案吗?

1 个答案:

答案 0 :(得分:1)

这是一个分组问题,您可以使用group by子句https://www.w3.org/TR/xquery-31/#id-group-by来解决:

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method 'xml';
declare option output:indent 'yes';


declare variable $players2 as element(PLAYER)* := (<PLAYER>
    <NAME>Joe</NAME>
    <SCORE>40</SCORE>
</PLAYER>,
<PLAYER>
    <NAME>Jane</NAME>
    <SCORE>20</SCORE>
</PLAYER>);

<PLAYERS>
{
  for $players in (PLAYERS/PLAYER, $players2)
  group by $name := $players/NAME
  return 
    <PLAYER>
    {
        $players[1]/NAME,
       <SCORE>
           {
               sum($players/SCORE)

           }
       </SCORE>
       }
       </PLAYER>    
}
</PLAYERS>

https://xqueryfiddle.liberty-development.net/b4GWV5