Thursday, August 4, 2011

Java XPath evaluation

I have put together a simple XPath parser.

Everything is very easy as long as you don't use Namespaces.

Here is a very nice trick to extract a NamespaceContext from the document you are parsing.

The alternative is providing your own implementation of NamespaceContext, either this way (see "public class MyNamespaceContext") or as shown in this post with NamespaceContextMap class

My first instance was using:

Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);

XPath xPath = XPathFactory.newInstance().newXPath();
NamespaceContext nsContext = new NamespaceContextMap("foo", "http://foo","bar", "http://bar", "def", "http://def");

String expression = ".//con3:xqueryTransform/con3:resource[1]/@ref";
XPathExpression xPathExpression = xPath.compile(expression);
return xPathExpression.evaluate(xmlDocument, XPathConstants.STRING);

Well, it doesn' work. Using "Document xmlDocument" in xPathExpression.evaluate fails to interpret namespaces.

I had to convert it to:
InputSource inputSource = new InputSource(xmlFile);
return xPathExpression.evaluate(inputSource, XPathConstants.STRING);

to make it work.


2 hours wasted.

I love XML, Xpaths and so on. What a solid technology.

No comments: