XQuery FLWOR表达式
精华
小牛编辑
193浏览
2023-03-14
FLWOR
是首字母缩略词,代表 - “For,Let,Where,Order by,Return”首字母缩略写。 以下列表显示了它们在FLWOR
表达式中所占的含义 -
- F -
For
- 选择所有节点的集合。 - L -
Let
- 将结果放在XQuery变量中。 - W -
Where
- 选择条件指定的节点。 - O -
Order by
- 按照条件对指定的节点进行排序。 - R -
Return
- 返回最终结果。
示例
以下是一个示例XML文档,其中包含有关书籍的信息。 我们将使用FLWOR
表达式来检索价格大于30
的书籍标题。
文件:books.xml 的文件内容 -
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">15天搞定Java</title>
<author>Maxsu</author>
<year>2015</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">15天搞定.Net</title>
<author>Susen</author>
<year>2018</year>
<price>40.50</price>
</book>
<book category="XML">
<title lang="en">3天搞定XQuery</title>
<author>Yizhi</author>
<author>Maxsu</author>
<year>2016</year>
<price>50.00</price>
</book>
<book category="XML">
<title lang="en">24小时搞定XPath</title>
<author>Jazz Bee</author>
<year>2019</year>
<price>16.50</price>
</book>
</books>
以下Xquery文档包含要在上述XML文档上执行的查询表达式。
文件:books.xqy -
let $books := (doc("books.xml")/books/book)
return <results>
{
for $x in $books
where $x/price>30
order by $x/price
return $x/title
}
</results>
文件:XQueryTester.java 的代码如下所示 -
//package com.yiibai.xquery;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQDataSource;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;
import com.saxonica.xqj.SaxonXQDataSource;
public class XQueryTester {
public static void main(String[] args){
try {
execute();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (XQException e) {
e.printStackTrace();
}
}
private static void execute() throws FileNotFoundException, XQException{
InputStream inputStream = new FileInputStream(new File("books.xqy"));
XQDataSource ds = new SaxonXQDataSource();
XQConnection conn = ds.getConnection();
XQPreparedExpression exp = conn.prepareExpression(inputStream);
XQResultSequence result = exp.executeQuery();
while (result.next()) {
System.out.println(result.getItemAsString(null));
}
}
}
运行上面示例代码,得到以下结果 -
D:\worksp\xquery>java -Djava.ext.dirs=D:\worksp\xquery\libs XQueryTester
<results>
<title lang="en">15天搞定.Net</title>
<title lang="en">3天搞定XQuery</title>
</results>
注:要验证结果,请将books.xqy 的内容(在XQuery开发环境章节中)替换为上面的XQuery表达式,然后执行XQueryTester java程序。