ilinsky / jquery-xpath

jQuery XPath plugin (with full XPath 2.0 language support)
180 stars 64 forks source link

jquery-xpath cannot resolve namespaces #20

Closed captainviet closed 7 years ago

captainviet commented 7 years ago

Hi,

I ended up trying the jquery-xpath library when looking for ways to return XML nodes from Xpath queries. I've tried the namespace resolver as suggested in the demo page with the following example.

xpath

I want to retrieve the node bk:book from the xml document specified by the string.

For the first query, I declared a namespace bk for the node book, and provided a resolver function returning the URI of the bk namespace, however nothing is returned.

For the second query, I changed the resolver function to return the default URI (default value of Element.namespaceURI, and also the same value as specified on the demo page), which is http://www.w3.org/1999/xhtml, I was able to get a result, this time however, the book node returned is not the one I wanted.

Can you help me verify whether the namespace resolver is working as you expected, and if it's still working, can you show me where I'm messing things up? Thank you in advance!

ilinsky commented 7 years ago

Hi @captainviet! The short answer is: you should not be using jQuery's HTML parser to construct XML DOM trees. Instead you shall be using XML parser, which supports namespaces - DOMParser browser API.

var tree = new DOMParser().parseFromString('<b><c:b xmlns:c="cns">d</c:b></b>', 'text/xml');
$(tree).xpath("//namespaced:b", function() {
    return "cns";
});

will return exactly one inner "b".

captainviet commented 7 years ago

Works like a charm!! Thank you very much!!