JDom, XPath and the saga of the invisible namespace

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="https://darrenhobbs.com/some/namespace/2008/10/15"
               xmlns:foo="https://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("https://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", "https://darrenhobbs.com/some/namespace/2008/10/15");

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

Advertisements

One thought on “JDom, XPath and the saga of the invisible namespace

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s