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"
  ... some stuff ...
  ... some foo stuff ...

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");
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.