XQuery - 如何返回XML元素列表

时间:2015-12-10 20:47:36

标签: xml xquery

我正在开展关于最近橄榄球世界杯的XML / XQuery项目。我一直在努力设计一个XQuery,它将返回每个团队参与的体育场列表。

我的XQuery看起来像这样:

for $a in doc("squads.xml")/tournament/squad,
$b in doc("match.xml")/tournament/match

where (($a/@country = $b/team1) or ($a/country = $b/team2))

return <team country ="{$a/@country}">
         <stadia>
           <stadium>{data($b/hostedBy)}</stadium>
         </stadia>
       </team>

并给出输出:

<team country="Argentina">
  <stadia>
    <stadium>Twickenham</stadium>
  </stadia>
</team

等等,每个体育场都列在一个单独的团队元素下。

理想情况下,我希望输出能够将体育场列为一个列表,如下所示:

<team country = "Argentina">
  <stadia>
    <stadium>Twikenham</stadium>
    <stadium>Leicester City Stadium</stadium>
    <stadium>Kingsholm Stadium</stadium>
  </stadia>
</team>

是否有一种简单的方法可以像显示的列表一样返回$ b / hostedBy?

squads.xml的样本:

<tournament>
  <squad country = "Argentina">
    <tier>1</tier>
    <result>4th</result>
    <games_played>7</games_played>
    ...
  </squad>
...
</tournament>

match.xml示例:

<tournament>
  <match>
      <matchNumber>8</matchNumber>
      <pool>C</pool>
      <team1>New Zealand</team1>
      <team2>Argentina</team2>
      <attendance>89,019</attendance>
      <hostedBy>Wembley Stadium</hostedBy>
  </match>
  ...
</tournament>

1 个答案:

答案 0 :(得分:1)

当你使用for $x in ..., $y in ...时会发生这种情况 - 它实质上是两个序列相乘。这通常会让人们从SQL中获取XQuery。你想要的是分组,你可以简单地添加一个嵌套循环,它连接外部循环的团队值:

for $squad in doc("squads.xml")/tournament/squad
return 
  <team country ="{$squad/@country}">
    <stadia>{
      for $match in doc("match.xml")/tournament/match
      where ($match/(team1 | team2) = $squad/@country)
      return <stadium>{ $match/hostedBy/string() }</stadium>
    }</stadia>
  </team>

如果您需要删除体育场馆,可以使用distinct-values

for $squad in doc("squads.xml")/tournament/squad
let $hosted-by := 
  for $match in doc("match.xml")/tournament/match
  where ($match/(team1 | team2) = $squad/@country)
  return $match/hostedBy/string()
return 
  <team country ="{$a/@country}">
    <stadia>{
      for $stadium in distinct-values($hosted-by)
      return <stadium>{ $stadium }</stadium>
    }</stadia>
  </team>