使用 SAXON S9API 评估 XPath 2.0 表达式

Evaluate XPath 2.0 Expression with SAXON S9API

我正在尝试执行 XPath 2.0 表达式,我可能遗漏了一些东西,我能够形成 XPathSelector,问题是如何 运行 组织上的选择器。w3c.dom.Document目的?我的代码如下:

public class XPath2Test {

public static void main(String[] args) throws Exception{

    String assemblyXPathString="/child::AssemblyBase/child::Assembly[attribute::roles='ALL' or contains(attribute::roles,$role)]";

    DOMParser parser=new DOMParser();
    FileInputStream fis=new FileInputStream("E:\workspaces\dev_werewolf\Platform_Manual\manual\UIFramework\RoleBasedUIAssembly2.xml");
    InputSource inputSource=new InputSource(fis);
    parser.parse(inputSource);
    Document document=parser.getDocument();


    Processor processor=new Processor(false);
    //processor.newDocumentBuilder().build(new File("E:\workspaces\dev_werewolf\Platform_Manual\manual\UIFramework\RoleBasedUIAssembly2.xml"));

    XPathCompiler compiler=processor.newXPathCompiler();
    compiler.declareVariable(new QName("role"));

    XPathExecutable executable=compiler.compile(assemblyXPathString);
    XPathSelector selector=executable.load();
    ArrayList<String> values=new ArrayList<>();
    values.add("CIO");
    selector.setVariable(new QName("role"),   XdmItem.makeSequence(values));

    //Now what???, how to run the quesry against the 'document'???
    selector.evaluate();//Exception

}//main closing

}//class closing

你需要做的

selector.setContextItem(item)

为 XPath 评估设置上下文节点,获取引用 DOM 文档根节点的项目的方法是

XdmNode item = processor.newDocumentBuilder().wrap(document);

请注意,只有在有充分理由的情况下,才应将 DOM 节点与 Saxon 一起使用;使用 Saxon 的内部树实现通常要快 5 到 10 倍。如果不关心是什么树,就用

XdmNode item = processor.newDocumentBuilder().build(
  new File("E:\workspaces\dev_werewolf\Platform_Manual\manual\UIFramework\RoleBasedUIAssembly2.xml"));