Tuesday, 6 July 2010

JDOM, XPath and Namespaces

The combination of JDOM and XPath seems to be the source of greatest woe for me of late - following my last blog post I spent (wasted) another day wrestling with these technologies on another sticking point. I'll not claim to be an XPath guru by any stretch (I am learning though!), but it does seem to throw some real curveballs. The latest was down to attempting to extract a List of JDOM sub-Elements from an Element using XPath.selectNodes(element). It continually refused to work, and seemed to be related to the fact that there was a namespace declaration in the root Element. After much head scratching and the help of the wider community, it came out that all that was needed was to wrap the Element in a Document. Can anyone with a deeper knowledge shed a light on why?

Here's the code that doesn't (but to my mind should) work:

Namespace ns = Namespace.getNamespace("srv","http://ess.com/ws/srv");
XPath filterXpression = XPath.newInstance("//srv:ItemCost");
filterXpression.addNamespace(ns);
List nodes = filterXpression.selectNodes(response);

And here's the working code:

Document build = new Document(response);
XPath filterXpression = XPath.newInstance("//srv:ItemCost");
List nodes = filterXpression.selectNodes(build);

You can get the full lowdown in this StackOverflow question.

No comments: