How to use Saxon XPath 2.0 with Java?

StellaMaris picture StellaMaris · Sep 22, 2015 · Viewed 9.6k times · Source

I like to use regular expressions in xPath, so I installed Saxon9.6

  1. My ${java.home} is C:\Program Files\Java\jdk1.7.0_51.
  2. I extracted saxonHE9-6-0-6J.zip in C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext
  3. and add saxonhe9.jar to my classpath variable.
  4. Then I created a jaxp.properties file under C:\Program Files\Java\jdk1.7.0_51\jre\lib and add the following lines:

    javax.xml.transform.TransformerFactory = net.sf.saxon.TransformerFactoryImpl javax.xml.xpath.XPathFactory","net.sf.saxon.xpath.XPathFactoryImpl

But now I cant find the examples like it is described on this page.

Answer

Michael Kay picture Michael Kay · Sep 22, 2015

In the latest release of Saxon, the JAR file no longer contains the meta-inf services file advertising it as a JAXP XPath factory provider. This is because too many applications were having problems: if the application is written and tested to work with the XPath 1.0 engine that comes with the JDK, there is a good chance it will fail if you try running it with Saxon's XPath 2.0 engine, and this was happening simply as a result of Saxon being on the class path. So if you want to use Saxon as your XPath engine, you now have to make the request explicit, e.g. by instantiating net.sf.saxon.xpath.XPathFactoryImpl directly.

By that I mean calling new XPathFactoryImpl() instead of XPathFactoryImpl.newInstance() because it's inherited from XPathFactory.

However, because the XPath 2.0 type system is so much richer than XPath 1.0, the JAXP interface is really quite clumsy, and I would recommend using the s9api interface instead.