XQuery FLWOR示例

假设有一系列项目,并且需要创建包含这些数据项目的报告。

我们将使用基本的XQuery FLWOR表达式来迭代序列中的每个数据项目。 FLWOR表达式的五个部分是:

  • for - 指定要选择的序列中的项目(可选)
  • let - 用于创建返回中使用的临时名称(可选)
  • where - 限制项目返回(可选)
  • order - 更改结果的顺序(可选)
  • return - 指定返回数据的结构(必需)

假设有一个样本文件,它的内容如下所示:

<books>
   <book>
      <title>Introduction to XQuery</title>
      <description>A beginner's guide to XQuery that covers sequences and FLOWR expressions</description>
      <type>softcover</type>
      <sales-count>155</sales-count>
      <price>19.95</price>
   </book>
  <book>
      <title>Document Transformations with XQuery</title>
      <description>How to transform complex documents like DocBook, TEI and DITA</description>
      <type>hardcover</type>
      <sales-count>105</sales-count>
      <price>59.95</price>
   </book>
   <!-- ...more books here.... -->
 </books>

下面是一个FLWOR表达式的简单示例,它只返回按标题排序的书籍的标题和价格:

for $book in doc(catalog.xml)/books/book
   let $title := $book/title/text()
   let $price := $book/price/text()
   where xs:decimal($price) gt 50.00
   order by $title
   return
      <book>
         <title>{$title}</title>
         <price>{$price}</price>
      </book>

此XQuery FLWOR表达式将返回价格超过50.00的所有书籍。 请注意,在for循环之后有两个let语句。还添加了where子句,将结果限制为价格超过50.00的书籍。 结果按标题排序,结果是新的书籍项目序列,其中包含价格和标题。

方法2: 使用“to”函数生成一系列值

还可以通过在序列中的两个数字之间放置关键字to来表示从一个数字到另一个数字的一系列值。

以下内容生成110之间的值列表。


<list>
   {for $i in (1 to 10)
      return
        <value>{$i}</value>
    }
</list>

方法3: 使用“at”函数生成一系列值

可以添加at $ my-counter为FLWOR循环中的每个数据项目添加数字计数器。

<items>
{
let $items := (apples,pears,oranges)
for $item at $count in $items
return
   <item id={$count}>
      {$item}
   </item>
}
</items>