使用SAXON S9API评估XPath 2.0表达式

时间:2018-01-08 11:04:04

标签: xpath saxon xpath-2.0

我正在尝试执行XPath 2.0表达式,我可能会遗漏一些东西,我能够形成XPathSelector,问题是如何在org.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

1 个答案:

答案 0 :(得分:1)

你需要做

selector.setContextItem(item)

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

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

请注意,如果你有充分的理由,你应该只使用Saxon的DOM节点;使用Saxon的内部树实现通常要快5到10倍。如果您不关心它是什么类型的树,请使用

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