I have a method for testing
private String getXmlVersion(byte[] xml) throws Exception {
String expression = "//Document/@version";
XPathFactoryImpl xPathFactory = new XPathFactoryImpl();
XPath xPath = xPathFactory.newXPath();
// DocumentBuilder db = new DocumentBuilderFactoryImpl().newDocumentBuilder();
// org.w3c.dom.Document xmlDoc = db.parse(new ByteArrayInputStream(xml));
XPathExpression ex = xPath.compile(expression);
// return "" + ex.evaluate(xmlDoc, XPathConstants.STRING);
return "" + ex.evaluate(new InputSource(new ByteArrayInputStream(xml)), XPathConstants.STRING);
}
I am using net.sf.saxon.dom.DocumentBuilderFactoryImpl and net.sf.saxon.xpath.XPathFactoryImpl. This version doesn't pass the test, cos XPath evaluates as empty string. But if I uncomment lines and start to use DocumentBuilder - XPath evaluates as expected and all tests will be passed.
In documentation I read that...
It is important to note that a compiled XPath expression can only be used with a source document that was built using the same Saxon Configuration.
Seems like when I use both DocumentBuilderFactoryImpl and XPathFactoryImpl, their Configuration is differs, but tests is passed. But what's wrong with a way when I use only XpathFactoryImpl?
I am using saxon 9.2.0.5.
can anyone help me by example of correct way using Saxon and XPath? Thank you for wasting your time for me and best regards.
EDIT I have tried to use s9api for that and here is a method example
private String getVersion(byte[] xmlData) throws Exception {
Processor proc = new Processor(false);
DocumentBuilder builder = proc.newDocumentBuilder();
XPathCompiler xpc = proc.newXPathCompiler();
xpc.declareNamespace("", "http://namespaceurl.info/ver2/rev2");
XPathSelector selector = xpc.compile("//Document/@version").load();
selector.setContextItem(builder.build(new StreamSource(new ByteArrayInputStream(xmlData))));
XdmItem xdmItem = selector.evaluateSingle();
return xdmItem == null ? "" : xdmItem.getStringValue();
}
This method pass a half of the tests, because it used explicitly defined namespace. But in different versions of documents namespaces is different.