Rah*_*ray 5 java xml xquery saxon xqj
我正在使用XQuery处理器Saxon.
现在我们在一个".xqy"文件中编写我们的XQuery,我们将在其中引用我们将在其上执行XQuery的XML文件.
请看下面的例子:
for $x in doc("books.xml")/books/book
where $x/price>30
return $x/title
Run Code Online (Sandbox Code Playgroud)
现在我想使用动态生成的XML而不是存储在某个路径中.比方说,我想在下面引用可用作字符串的XML.
怎么做?
String book=
<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>
Run Code Online (Sandbox Code Playgroud)
Java代码:
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找一种使用 Java绑定查询输入(上下文项)的方法,我建议使用 Saxon 的 S9API(Java 中用于 XSLT、XPath 和 XQuery 处理的最直观的 API)。
以下是如何实例化 Saxon、编译查询、解析输入并使用绑定的输入文档作为其上下文项评估查询:
// the Saxon processor object
Processor saxon = new Processor(false);
// compile the query
XQueryCompiler compiler = saxon.newXQueryCompiler();
XQueryExecutable exec = compiler.compile(new File("yours.xqy"));
// parse the string as a document node
DocumentBuilder builder = saxon.newDocumentBuilder();
String input = "<xml>...</xml>";
Source src = new StreamSource(new StringReader(input));
XdmNode doc = builder.build(src);
// instantiate the query, bind the input and evaluate
XQueryEvaluator query = exec.load();
query.setContextItem(doc);
XdmValue result = query.evaluate();
Run Code Online (Sandbox Code Playgroud)
请注意,如果 Java 代码生成 XML 文档,我强烈建议您使用 S9API 直接在内存中构建树,而不是将 XML 文档生成为字符串,然后对其进行解析。如果可能的话。