如何在 XQuery 中使用 FLOWR return 这家书店的第三本书?

how to return the third book from this bookstore using FLOWR in XQuery?

如何return这家书店的第三本书?

declare context item := document{
<bookstore>

<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

<book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

<book category="web" cover="paperback">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

</bookstore>
};

let $date := current-date()
for $ctx in context
return $ctx/bookstore/book[3]

到目前为止我只得到一个空白结果:

PS C:\Users\thufir\Desktop\basex> PS C:\Users\thufir\Desktop\basex> basex contextDoc.xq PS C:\Users\thufir\Desktop\basex>

您需要调整for子句并使用符号引用上下文,如下所示:

XQuery

declare context item := document {
<bookstore>
<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="web" cover="paperback">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</bookstore>
};

for $ctx in ./bookstore/book[3]
return $ctx

Output

<book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

当您从 for 循环迭代时,您会在 $ctx 变量中获得元素书店。你通过写名字($ctx)检查这个。所以你不需要把 bookstore 元素再写成 $ctx/bookstore/book[3]。只需从您的代码中删除书店并将查询编写为 $ctx/book[3].

改变一下

for $ctx in context

for $ctx in .

查看 https://xqueryfiddle.liberty-development.net/b4GWVn

你的问题标题是 "using a FLWOR expression",但是 FLWOR 表达式对于这样一个简单的查询来说太过分了。

@YitzhakKhabinsky 提供了正确答案:

for $ctx in ./bookstore/book[3] return $ctx

但是表达式 for $X in Y return $X 只是 Y 的一种冗长的表达方式,所以这简化为

./bookstore/book[3]

或更简单

bookstore/book[3]