我有一些 XML 的字符串表示,我想在内存中对其运行 XQuery。我一直在玩撒克逊人并想出了一个解决方案,但为了让它发挥作用,我做了一件丑陋的、丑陋的事情。我有一种感觉,这是因为我对撒克逊人缺乏经验。这是一些有效的代码:
import javax.xml.transform.URIResolver;
import net.sf.saxon.Configuration;
import net.sf.saxon.s9api.*;
public class XmlTest {
public static void main(String[] args) {
try {
final String tableXml =
"<table>" +
" <columns>" +
" <column>Foo</column><column>Bar</column>" +
" </columns>" +
" <rows>" +
" <row><cell>Foo1</cell><cell>Bar1</cell></row>" +
" <row><cell>Foo2</cell><cell>Bar2</cell></row>" +
" </rows>" +
"</table>";
Configuration saxonConfig = new Configuration();
Processor processor = new Processor(saxonConfig);
XQueryCompiler xqueryCompiler = processor.newXQueryCompiler();
XQueryExecutable xqueryExec = xqueryCompiler
.compile("<result>{"
+ "doc('')/table/rows/row/cell/text()='Foo2'"
+ "}</result>");
XQueryEvaluator xqueryEval = xqueryExec.load();
xqueryEval.setSource(new SAXSource(new InputSource(
new StringReader(tableXml))));
XdmDestination destination = new XdmDestination();
xqueryEval.setDestination(destination);
// Avert your eyes!
xqueryEval.setURIResolver(new URIResolver() {
@Override
public Source resolve(String href, String base) throws TransformerException {
return new StreamSource(new StringReader(tableXml));
}
});
xqueryEval.run();
System.out.println(destination.getXdmNode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
我遇到的问题是 XML 文档的基本 URI。由于它在内存中,因此没有可参考的基础文档。我知道 XML 将始终是自包含的,因此我决定重写URIResolver
以仅将包装在Source
类型对象中的 XML 传回。我知道这是错误的,但它有效。如果我不这样做,我会收到Content not allowed in prolog
错误消息。从错误消息的其余部分看来,它正在尝试将当前目录作为 XML 文件读取。那部分对我来说有点神秘,但我愿意学习!有没有正确的方法来做我想做的事?