以下是一个示例XML文档,其中包含各种图书的书店记录.
<?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>70.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文档,其中包含要在上述XML文档上执行的查询表达式.目的是获取价格大于30的那些XML节点的标题元素.
for $x in doc("books.xml")/books/book where $x/price>30 return $x/title
<title>Learn .Net in 24 hours</title> <title>Learn XQuery in 24 hours</title>
要验证结果,请替换 books.xqy 的内容(在环境设置章节中给出)使用上面的XQuery表达式并执行XQueryTester java程序.
让我们理解上面XQuery表达式的每一部分.
doc("books.xml")
doc()是使用的XQuery函数之一找到XML源.在这里,我们通过了"books.xml".考虑到相对路径,books.xml应该位于books.xqy所在的相同路径中.
doc("books.xml")/books/book
XQuery大量使用XPath表达式来定位所需的XML部分进行哪种搜索.在这里,我们选择了书籍节点下可用的所有书籍节点.
for $ x in doc("books.xml")/books/book
XQuery将xml数据视为对象.在上面的示例中,$ x表示所选节点,而for循环遍历节点集合.
where $x/price>30
由于$ x代表所选节点,"/"用于获取值所需要素; "where"子句用于在搜索结果上添加条件.
return $x/title
由于$ x代表所选节点,"/"用于获取所需元素,价格,标题的值; "return"子句用于从搜索结果中返回元素.