XQuery - 如果然后否则
XQuery 提供了一个非常实用的 if-then-else 结构,用来检查传入的输入值的有效性。以下是 if-then-else 结构的语法。
语法
if (condition) then ... else ...
示例
我们将使用以下 books.xml 文件,并对它应用包含 if-then-else 结构的 XQuery 表达式,以检索价格值大于 30 的那些书的标题。
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>40.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
<year>2013</year>
<price>50.00</price>
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
<price>16.50</price>
</book>
</books>
以下 XQuery 表达式将应用于上述 XML 文档。
books.xqy
<result>
{
if(not(doc("books.xml"))) then (
<error>
<message>books.xml does not exist</message>
</error>
)
else (
for $x in doc("books.xml")/books/book
where $x/price>30
return $x/title
)
}
</result>
输出
<result> <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> </result>
验证结果
要验证结果,请将 环境设置 章节中给出的 books.xqy 的内容替换为上述 XQuery 表达式,然后执行 XQueryTester java 程序。
广告