在Java中使用SAXON Xpath引擎

时间:2009-05-29 14:19:23

标签: java xpath saxon

这是我的代码:

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)

当我通过org.apache.xpath.compiler.XPathParser清楚地创建工厂时,这意味着Java正在使用net.sf.saxon.xpath.XPathFactoryImpl类。

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

我做错了什么?

1 个答案:

答案 0 :(得分:11)

来自撒克逊的例子:

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

工作正常。