[jdom-interest] again xpath with default namespace

Laurent Bihanic laurent.bihanic at atosorigin.com
Thu May 3 00:43:44 PDT 2007


Hi,

florianwendland at freenet.de wrote:
> i have a problem by creating an xpath expression with an default 
> namespace. The xpath expression didn't select the nodes, although i have 
> added the namespace to the xpath by calling 
> xp.addNamespace("http://www.test.de");

There is no default namespace in XPath.
So you have to use a namespace prefix in your XPath expressions. You can 
choose any prefix as there is no relationship between the prefixes used in 
XPath and the ones in the document: prefixes are just shortcuts and the 
matching is done on the actual namespace URIs.

> My document looks like:
> 
> <test xmlns="http://www.test.de">
>     <node>
>     </node>
> </test>
> 
> The source:
> 
> XPath xp = XPath.newInstance("/test/node");
> xp.addNamespace(ExiilConstants.NS);
> xp.selectNodes(document);
> 
> Result of the list is allways 0.

The following should work:
XPath xp = XPath.newInstance("/x:test/x:node");
xp.addNamespace("x", "http://www.test.de");
xp.selectNodes(document);

If you want to use a JDOM Namespace object, you must create one with a prefix:
Namespace ns = Namespace.getNamespace("x", "http://www.test.de");
xp.addNamespace(ns);

Laurent



More information about the jdom-interest mailing list