【问题标题】:Evaluate XPath 2.0 Expression with SAXON S9API使用 SAXON S9API 评估 XPath 2.0 表达式
【发布时间】:2018-01-08 11:04:03
【问题描述】:

我正在尝试执行 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

【问题讨论】:

    标签: xpath saxon xpath-2.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"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      相关资源
      最近更新 更多