Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Saxon XPath 2.0 with Java?

Tags:

java

xpath

saxon

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.

like image 808
StellaMaris Avatar asked Dec 05 '22 20:12

StellaMaris


2 Answers

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.

like image 155
Michael Kay Avatar answered Dec 08 '22 11:12

Michael Kay


I use Saxon-HE 9.8.0-5 like this:

Processor processor = new Processor(false);
XdmNode xdm = processor.newDocumentBuilder().build(new StreamSource(new StringReader(xml)));
XdmValue result = processor.newXPathCompiler().evaluate(query, xdm);

StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.size(); i++) {
    sb.append(result.itemAt(i).getStringValue());
    if (i + 1 != result.size()) {
        sb.append('\n');
    }
}
like image 42
Vilius Avatar answered Dec 08 '22 11:12

Vilius