4

In Firefox JavaScript console:

parser = new DOMParser();

foo = parser.parseFromString('<foo></foo>', "text/xml");
res = foo.evaluate("/foo", foo, null, 0, null);
res.iterateNext();
> [object Element]

foo = parser.parseFromString('<foo xmlns="http://foo.bar.baz/quux"></foo>', "text/xml");
res = foo.evaluate("/foo", foo, null, 0, null);
res.iterateNext();
> null

res = foo.evaluate("*[1]", foo, null, 0, null);
res.iterateNext();
> [object Element]

If an XML document doesn't contain an xmlns, it gets parsed and queried correctly. If it does, we are not able to query by tag and attribute names anymore. However, querying with wildcards and indexes does work. The same is observed in Chrome. Creating and using default namespace resolver, as well as custom one, doesn't help. Any suggestions?

Jens Erat
  • 37,523
  • 16
  • 80
  • 96
Dimitri
  • 301
  • 2
  • 13

1 Answers1

4

You have to do two things when dealing with namespaces.

  1. Use the namespace in your XPath expression. As there is no prefix in your document, I just chose ns -- better go with something more descriptive in real world code.
  2. Add a namespace resolver, which actually is a function that gets passed as third parameter to evaluate(...).

Putting everything together, your code would look like this:

parser = new DOMParser();
foo = parser.parseFromString('<foo xmlns="http://foo.bar.baz/quux"></foo>', "text/xml");
res = foo.evaluate("/ns:foo", foo, function(prefix) {
    if (prefix === 'ns') {
        return 'http://foo.bar.baz/quux';
    } else {
        return null
    }
}, 0, null);
res.iterateNext();

Which returns as expected:

<foo xmlns="http://foo.bar.baz/quux"></foo>

Your third query has results because you're using the wildcard matcher * which ignores namespaces. An alternative XPath expression without registering a namespace, but using the wildcard matcher would be

//*[local-name() = 'foo']
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
  • Excellent! Thanks a lot. Earlier I've tried similar code in Java with javax.xml.xpath.XPathExpression, and no additional namespace handling was required, I wonder why. Seems like Java XPath implementation is less strict in the context of XML namespaces. – Dimitri Oct 18 '13 at 09:08