8

Here is my code :

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();
    }

}

And I get this :

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)

Which means Java is using org.apache.xpath.compiler.XPathParser class when I clearly created my factory through net.sf.saxon.xpath.XPathFactoryImpl.

(I actually only need to put some matches in my xpaths... so if any solution not involving Saxon is known, consider my need reached).

What am I doing wrong ?

joergl
  • 2,850
  • 4
  • 36
  • 42
g andrieu
  • 2,081
  • 3
  • 14
  • 10

1 Answers1

12

From Saxon examples :

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

Works fine.

g andrieu
  • 2,081
  • 3
  • 14
  • 10
  • If you are confused about the jar files, you need to add saxon core and saxon dome to your dependencies in order to make it work, or you will get a ""Cannot locate an object model implementation for nodes of class com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl" Exception – Arash Oct 05 '11 at 18:31
  • How do I do the opposite, that is, force it to use the default XPathFactory in the JVM (instead of Saxon)? – james.garriss Apr 19 '12 at 19:26
  • No James, because we want to use XPath 2.0 functions like 'matches' here. – Donatello Jul 16 '14 at 15:55
  • Anyway, this workaround does not work in my case, without error or warning, but empty value after evaluation of any function.. NB : I use the docFactory.setNamespaceAware(false); – Donatello Jul 16 '14 at 16:09