考虑以下 XML:
<bib>
<book year="1994">
<title>TCP/IP Illustrated</title>
<author><last>Stevens</last><first>W.</first></author>
<publisher>Addison-Wesley</publisher>
<price>65.95</price>
</book>
<book year="2000">
<title>Data on the Web</title>
<author><last>Abiteboul</last><first>Serge</first></author>
<author><last>Buneman</last><first>Peter</first></author>
<author><last>Suciu</last><first>Dan</first></author>
<publisher>Morgan Kaufmann Publishers</publisher>
<price>39.95</price>
</book>
<book year="1999">
<title>The Economics of Technology and Content for Digital TV</title>
<editor><last>Gerbarg</last><first>Darcy</first><affiliation>CITI</affiliation></editor>
<publisher>Kluwer Academic Publishers</publisher>
<price>129.95</price>
</book>
</bib>
我知道以下 XQuery 查询
for $book in doc(“books.xml”)//book
where $book/price>60
return <expensiveBook>
{ $book/title/text() }
</expensiveBook>
将准确返回价格大于 60 的两本书的标题:
<expensiveBook>TCP/IP Illustrated</expensiveBook>
<expensiveBook>The Economics of Technology and Content for Digital TV</expensiveBook>
改为以下查询:
let $books := doc(“books.xml”)//book
where $books/price > 60 (: existential... :)
return <expensiveBooks>
{ $books/title }
</expensiveBooks>
将返回 XML 文档中的全部三本书:
<expensiveBooks>
<title>TCP/IP Illustrated</title>
<title>Data on the Web</title>
<title>The Economics of Technology and Content for Digital TV</title>
</expensiveBooks>
我不明白为什么会发生这种情况,我不应该将整本书放入用“let”声明的变量中,然后用 where 子句过滤它吗?为什么还返回价格低于 60 的《Web 数据》一书?
我无法理解的另一件奇怪的事情是像下面这样的查询:
let $books in doc(“books.xml”)//book[price>60]
return <expensiveBook>
{ $books/title }
</expensiveBook>
仅正确返回价格大于 60 的两本书:
<expensiveBooks>
<title>TCP/IP Illustrated</title>
<title>The Economics of Technology and Content for Digital TV</title>
</expensiveBooks>
这里的情况如何?为什么这种行为不是我所期望的? where 子句对于 let 和 for 子句的作用是否不同?最后一个查询怎么样,其中使用了“let”子句,但通过 XPath 语法 [element=value] 指定价格元素?
一如既往地感谢您的帮助:)
最佳答案
我认为您需要找到一些有关 XPath 和 XQuery 的基本资源。 当你说:
let $books := doc(“books.xml”)//book
where $books/price > 60 (: existential... :)
return <expensiveBooks>
{ $books/title }
</expensiveBooks>
这意味着:将$books绑定(bind)到所有book元素的序列,现在考虑序列中books的所有price元素的序列:如果其中任何一个超过60,则返回所有title元素的序列$books 中的任何 book 元素,包裹在一个元素中。所以你要么得到全部,要么得不到。
您的第一个查询是:迭代图书元素的序列,如果我现在拥有的图书元素的价格超过 60,则返回标题。
对 XPath 进行约束的查询:
let $books in doc(“books.xml”)//book[price>60]
return <expensiveBook>
{ $books/title }
</expensiveBook>
表示:构造一个包含价格子元素大于 60 的所有书籍元素的序列,并返回一个由这些书籍的所有标题序列组成的元素,并包装在一个元素中。
Let 绑定(bind)一个变量; for 依次将变量绑定(bind)到序列的每个成员。序列上的路径表达式会产生其他序列。 “=”和“>”是存在运算符,它们对序列进行操作并返回单个 bool 结果。
关于xml - "where"子句上的 "for"和 "where"子句上的 "let"之间的 XQuery 差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40533404/