xquery用于对来自xml文件的数据进行分组

时间:2013-12-03 20:16:24

标签: xml xquery basex

我正在尝试为我的xml文件运行xquery。这是我输入的xml文件:

<?xml version="1.0" ?>
<authors>
   <author><name> Steven</name>
     <title>advanced</title>
     <title>TCPIP</title>
   </author>
   <author><name> George</name>
     <title>DataMining</title>
     <title>Economic</title>
   </author>
   <author><name> Den</name>
    <title>TCPIP</title>
    <title>Economic</title>
   </author>
</authors>

我正在尝试对每个标题进行分组,并计算每个标题的作者数量。书籍应按作者数量的递增顺序列出。对于每本书,按字母顺序输出其标题,作者数量和所有作者的姓名。最后,输出应该是这样的:

<bib>
 <book authors="1">
  <title>Advanced</title>
  <author>Steven</authhor>
 </book>
 <book authors="1">
  <title>DataMining</title>
  <author>George</author>
 </book>
 <book authors="2">
  <title>TCPIP</title>
  <author>Den</author>
  <author>Steven</author>
 </book>
 <book authors="2">
  <title>Economic</title>
  <author>Den</author>
  <author>George</author>
 </book>
</bib>

这是我的代码不起作用:(。有任何帮助。请尽可能纠正我的代码而不是编写新代码,因为我希望答案看起来像我的答案。

<bib>
{for $a in doc('test')//authors
let $T:={for $c in doc ('test')//authors/author[title=$a/author/title]
order by count($T)
return <book authors="{count($T)}">
{<title> {distinct-values($T/title)}
for $x in $T
order by $x/name()
return <author>{$x/name()}</author>}
</book>}
</bib>

我认为问题出在我尝试使用let命令的部分。据我所知,我可以通过let命令对数据进行分组。我尝试使用XML文件中的每个标题来抓取所有作者,然后计算作者的数量并按名称对它们进行排序。我使用此链接:http://basex.org/products/live-demo/来测试我的答案。

1 个答案:

答案 0 :(得分:1)

正如Daniel Haley建议的那样,你应该反过来这样做,即迭代每个标题并寻找撰写这个特定标题的作者。您可以使用distinct-valuesgroup by。以下应该有效:

<bib>
{
  let $titles := distinct-values(doc('test')//title)
  for $t in $titles
  let $authors := doc('test')//author[title = $t]
  order by count($authors)
  return
    <book authors="{count($authors)}">
      <title>{$t}</title>
      {
        for $a in $authors
        order by $a/name
        return <author>{$a/name/string()}</author>
      }
    </book>
}
</bib>