4

I have below XML which contains a 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 running following code expecting some result in return

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 gone through

Looking forward for any help.

Community
  • 1
  • 1
Samiron
  • 5,169
  • 2
  • 28
  • 55
  • Got this really helpful - http://stackoverflow.com/a/3439776/1160106. Trying the updated part of the answer. – Samiron Jan 15 '13 at 11:22

1 Answers1

4

Unprefixed names in XPath always mean "no namespace" - they don't respect the default namespace declaration. You need to use a 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 where the original document didn't, as long as the namespace URI that is bound to the prefix in the XPath namespace context is the same as the URI that is bound by xmlns in the document.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • Just another hint, you have to add all namespaces of all tags used in your xpath expression not only the qualified ones. In my case the problem was that it was missing the addNamespace of my unqualified namespace :( – Jonas Fagundes Oct 09 '13 at 18:51