XQuery符合XPath.它使用XPath表达式来限制XML集合上的搜索结果.有关如何使用XPath的更多详细信息,请参阅我们的 XPath教程.
回想下列内容我们之前用来获取书籍列表的XPath表达式.
doc("books.xml")/books/book
我们将使用books.xml文件并对其应用XQuery.
<?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title>Learn Java in 24 Hours</title> <author>Robert</author> <year>2005</year> <price>30.00</price> </book> <book category="DOTNET"> <title>Learn .Net in 24 hours</title> <author>Peter</author> <year>2011</year> <price>40.50</price> </book> <book category="XML"> <title>Learn XQuery in 24 hours</title> <author>Robert</author> <author>Peter</author> <year>2013</year> <price>50.00</price> </book> <book category="XML"> <title>Learn XPath in 24 hours</title> <author>Jay Ban</author> <year>2010</year> <price>16.50</price> </book> </books>
我们在这里给出了三个版本的XQuery语句,它们实现了显示价格值大于30的书籍标题的相同目的.
(: read the entire xml document :) let $books := doc("books.xml") for $x in $books/books/book where $x/price > 30 return $x/title
<title>Learn .Net in 24 hours</title> <title>Learn XQuery in 24 hours</title>
(: read all books :) let $books := doc("books.xml")/books/book for $x in $books where $x/price > 30 return $x/title
<title>Learn .Net in 24 hours</title> <title>Learn XQuery in 24 hours</title>
(: read books with price > 30 :) let $books := doc("books.xml")/books/book[price > 30] for $x in $books return $x/title
<title>Learn .Net in 24 hours</title> <title>Learn XQuery in 24 hours</title>
要验证结果,请替换 books.xqy (在环境设置章节中给出)使用上面的XQuery表达式并执行XQueryTester java程序.