xQuery 1.0,元素计数

xQuery 1.0, element counting

我在编写 XQuery 时遇到问题。我有这个 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<book>
  <title>Data</title>
  <author>Serge Abiteboul</author>
  <author>Peter Buneman</author>
  <author>Dan Suciu</author>
  <section id="intro" difficulty="easy" >
    <title>Chapter1</title>
    <p>Text ... </p>
    <section>
      <title>SubChapter1</title>
      <p>Text ... </p>
    </section>
    <section>
      <title>SubChapter2</title>
      <p>Text ... </p>
      <figure height="400" width="400">
        <title>Figure1</title>
        <image source="csarch.gif"/>
      </figure>
      <p>Text ... </p>
    </section>
  </section>
  <section id="syntax" difficulty="medium" >
    <title>Chapter2</title>
    <p>Text ... </p>
    <figure height="200" width="500">
      <title>Figure2</title>
      <image source="graphs.gif"/>
    </figure>
    <p>Text ... </p>
    <section>
      <title>SubChapter3</title>
      <p>Text ... </p>
    </section>
    <section>
      <title>SubChapter6</title>
      <p>Text ... </p>
      <figure height="250" width="400">
        <title>Figure3</title>
        <image source="relations.gif"/>
      </figure>
    </section>
    <section>
      <title>SubChapter5</title>
      <p>Text ... </p>
    </section>       
  </section>
</book> 

我必须编写一个 Xquery 来计算章节中的每个子章节,以及每个章节中的每个数字。到目前为止我已经到了这个地步:

    for $x in doc("file.xml")/book
    return ((<main>{data($x/title)}</main>),
(<mChapter nrSubChapter="{count($x/section/title)}" nrFigure="{count($x/section/section/figure)}">{***data($x/section/title)***}</mChapter>),
    (<mChapter nrSubChapter="{count($x/section/title}" nrFigures="{count($x//figure)}">{***data($x/section/title)***}</mChapter>))

另外我也不知道怎么把章节标题放在有***的地方

您的示例查询中有几处我不明白。首先,for $x in doc(...)/* 不会遍历多个节点,因为 XML 文档中只有一个根元素(这是一个谎言,但为了简单起见,我们假设没有例外)。

您对括号的使用也使查询很难阅读。为什么不为输出使用更自然的 XML 结构?

你想要做的是从整本书(书名)中检索一些东西,然后遍历章节,然后对每个章节,循环它自己的(子-)节。

let $book := doc('file.xml')/book
return
   <result>
      <main>{ xs:string($book/title) }</main>
      {
         for $section in $book/section
         return
            <chapter nrSubChapter="{ count($section/section) }"
                     nrFigure="{ count($section/figure) }">
               <title>{ xs:string($section/title) }</title>
               {
                  for $sub in $section/section
                  return
                     <section nrFigure="{ count($sub/figure) }">
                        <title>{ xs:string($sub/title) }</title>
                     </section>
               }
            </chapter>
      }
   </result>

如果你可以有多个级别的部分,你将不得不使用递归。

此外,正如 Jens 所说,您没有告诉我们您想要的确切输出格式,所以我只是给您一个解决方法,您必须根据您的具体要求进行调整。

PS:注意我没有测试代码。