在Java中使用SAXON Xpath引擎

8

这里是我的代码:

public static void main(String[] args) {

    // System.setProperty(
    // "javax.xml.xpath.XPathFactory", 
    // "net.sf.saxon.xpath.XPathFactoryImpl");

    String xml="<root><a>#BBB#</a><a>#CCC#</a><b><a>#DDD#</a></b></root>";
    try{
        JDocument dom = new JDocument(xml);

        XPathFactory factory = net.sf.saxon.xpath.XPathFactoryImpl.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//a[matches(.,'#...#')]");

        Object result = expr.evaluate(dom, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        Nodes sharped = new Nodes(nodes);

        for (Node n:sharped){
            System.out.println(n.toString());
        }
    }
    catch(Exception e){
        e.printStackTrace();
    }

}

我得到这个:
javax.xml.transform.TransformerException: Impossible to find the function : matches
at org.apache.xpath.compiler.XPathParser.error(XPathParser.java:608)
at org.apache.xpath.compiler.XPathParser.FunctionCall(XPathParser.java:1505)
at org.apache.xpath.compiler.XPathParser.PrimaryExpr(XPathParser.java:1444)
at org.apache.xpath.compiler.XPathParser.FilterExpr(XPathParser.java:1343)
at org.apache.xpath.compiler.XPathParser.PathExpr(XPathParser.java:1276)

这意味着当我明确通过net.sf.saxon.xpath.XPathFactoryImpl创建我的工厂时,Java正在使用org.apache.xpath.compiler.XPathParser类。 (实际上,我只需要在我的xpath中放置一些matches...因此,如果已知不涉及Saxon的任何解决方案,请考虑满足我的需求)。 我做错了什么?
1个回答

12

来自Saxon的例子:

System.setProperty("javax.xml.xpath.XPathFactory:"+NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl");
XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);

运行良好。


如果您对jar文件感到困惑,您需要将Saxon Core和Saxon Dome添加到依赖项中才能使其正常工作,否则您将会得到一个“无法定位com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl类节点的对象模型实现”的异常信息。 - Arash
我该如何做相反的操作,即强制它使用JVM中的默认XPathFactory(而不是Saxon)? - james.garriss
不,James,因为我们想在这里使用XPath 2.0函数,比如'matches'。 - Donatello
无论如何,这种解决方法在我的情况下不起作用,没有错误或警告,但在任何函数评估后为空值。 注:我使用docFactory.setNamespaceAware(false); - Donatello

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接