Posts Tagged ‘java’

JDom, XPath and the saga of the invisible namespace

Monday, September 15th, 2008

JDOM’s XPath implementation has (in my opinion)  big glaring bug with respect to its handling of the default namespace. That’s a namespace that looks a bit like this in the XML:

<?xml version="1.0" encoding="utf-8"?>
<myRootElement xmlns="http://darrenhobbs.com/some/namespace/2008/10/15"
               xmlns:foo="http://darrenhobbs.com/some/foo/namespace">
 <myChildElement>
  ... some stuff ...
 </myChildElement>
 <foo:aFooElement>
  ... some foo stuff ...
 </foo:aFooElement>
</myRootElement>

Note the ‘xmlns=…’, denoting the default namespace. As opposed to ‘xmlns:foo=’ which denotes the ‘foo’ namespace.

Let’s say I wanted to run an XPath query for: ‘//myChildElement’:

XPath xPath = XPath.newInstance("//myChildElement");
xPath.addNamespace(Namespace.getNamespace("http://darrenhobbs.com/some/namespace/2008/10/15"));
List nodes = xPath.selectNodes(aDocument);

This will never work. XPath does not play nicely with default namespaces. The solution is to register the same namespace URI against a made-up prefix and change the XPath like so:

XPath xPath = XPath.newInstance("//dh:myChildElement");
xPath.addNamespace("dh", "http://darrenhobbs.com/some/namespace/2008/10/15");

The query should then work.  This is not a new problem.