Using xpath in xml with default namespace using XOM

I have below XML which contains default namespace

<?xml version="1.0"?> <catalog xmlns="http://www.edankert.com/examples/"> <cd> <artist>Stoat</artist> <title>Future come and get me</title> </cd> <cd> <artist>Sufjan Stevens</artist> <title>Illinois</title> </cd> <cd> <artist>The White Stripes</artist> <title>Get behind me satan</title> </cd> </catalog> 

And Im runs the following code, expecting some result in reverse

 Element rootElem = new Builder().build(xml).getRootElement(); xc = XPathContext.makeNamespaceContext(rootElem); xc.addNamespace("", "http://www.edankert.com/examples/"); Nodes matchedNodes = rootElem.query("cd/artist", xc); System.out.println(matchedNodes.size()); 

But the size is always 0.

I went through

Looking forward to any help.

+4
source share
1 answer

Unprefixed names in XPath always mean "no namespace" - they do not respect the default namespace declaration. You need to use the prefix

 Element rootElem = new Builder().build(xml).getRootElement(); xc = XPathContext.makeNamespaceContext(rootElem); xc.addNamespace("ex", "http://www.edankert.com/examples/"); Nodes matchedNodes = rootElem.query("ex:cd/ex:artist", xc); System.out.println(matchedNodes.size()); 

It doesn’t matter that the XPath expression uses a prefix that was not the original document if the namespace URI associated with the prefix in the context of the XPath namespace matches the URI that is associated with xmlns in the document.

+4
source

All Articles