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

后端 未结 1 692
刺人心
刺人心 2021-01-14 18:38

In Firefox JavaScript console:

parser = new DOMParser();

foo = parser.parseFromString(\'\', \"text/xml\");
res = foo.evaluate(\"/foo\         


        
1条回答
  •  醉梦人生
    2021-01-14 19:10

    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('', "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:

    
    

    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']
    

    0 讨论(0)
提交回复
热议问题