DOM XPath query doesn't work when a xmlns is given

妖精的绣舞 提交于 2019-12-05 18:23:00

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']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!