开发者

Can XML be parsed reliably using jQuery's $(responseXML) syntax?

I'm currently looking for an easy way to extract information from server XML responses using JavaScript. jQuery seems like a good candidate for this.

When it comes to parsing XML with jQuery, I keep coming across code examples similar to the following snippet:

function parseXml(responseXml) {

    $(responseXml).find('someSelector')...

}

Yet, the jQuery Core documentation (quotation below) clearly states that you aren't supposed to do that:

jQuery( html, [ ownerDocument ] )

html A string of HTML to create on the fly. Note that this parses HTML, not XML.

— http://api.jquery.com/jQuery/#j开发者_运维问答Query2

This makes me wonder why so many online resources nevertheless suggest parsing XML via $(responseXml). Does this generally work without any problems, despite what the API documentation says? In what cases will parsing XML like this actually not work?


I do not know if my experience can be generalized, but I had my share of problems parsing SOAP messages with jQuery. This is probably not down to jQuery (as you point out the documentation disrecommends it).

Anyway, you asked for specifics: I found everything with namespaces to be problematic. Of course, for genuine namespace awareness, you'd need something that can resolve namespace prefixes to a namespace URI. I never expected jQuery to be able to do that, but even matching only prefixes didn't work out for me. This is especially problematic for me because the SOAP messages I am dealing with easily mix 4 or 5 namespaces. So I went back to doing DOM traversal myself to tackle this problem (which has its own set of problems)

That said, I do expect jQuery to be able to handle xhtml documents (as long as the tag names aren't prefixed), and I would expect it to work too for other xml documents that do not use namespace prefixes.


the jQuery ajax documentation adds http://api.jquery.com/jQuery.ajax/:

dataType

"xml": Returns a XML document that can be processed via jQuery.

...If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors...

Also at http://api.jquery.com/jQuery/

When XML data is returned from an Ajax call, we can use the $() function to wrap it in a jQuery object that we can easily work with. Once this is done, we can retrieve individual elements of the XML structure using .find() and other DOM traversal methods.


Your link actually points to the usage of jQuery( html ) that deals with creation of elements from strings, i.e.

$('<a href="..."></a>')

The one that your code uses is jQuery( element ) which is fine for XML.

since responseXML is XML, not a string, you're free to use jQuery() on it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜