【问题标题】:Using SAXON Xpath engine in Java在 Java 中使用 SAXON Xpath 引擎
【发布时间】:2010-10-29 21:35:40
【问题描述】:

这是我的代码:

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 类。

(我实际上只需要在我的 xpaths 中放一些 matches...所以如果知道任何不涉及 Saxon 的解决方案,请考虑满足我的需求)。

我做错了什么?

【问题讨论】:

    标签: java xpath saxon


    【解决方案1】:

    来自撒克逊人的例子:

    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 添加到您的依赖项中以使其工作,否则您将得到一个 ""Cannot locate an object model implementation for com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl 类的节点"异常
    • 我该如何做相反的事情,即强制它使用JVM中默认的XPathFactory(而不是Saxon)?
    • 没有 James,因为我们想在这里使用 XPath 2.0 函数,比如“匹配”。
    • 无论如何,这种解决方法在我的情况下不起作用,没有错误或警告,但在评估任何函数后为空值.. 注意:我使用 docFactory.setNamespaceAware(false);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多