Reputation: 745
I'm calling a webpage via ajax. Part of it's response is a small block of XML.
I tried parsing it but jQuery only seems to find some of the nodes. For example:
<aaa>
<text>bbb</text>
<image>test</image>
</aaa>
It finds text just fine but never finds the image node.
But if I change the spelling from "image" to "zimage" it finds it. Is the word "image" reserved when parsing XML through jQuery?
My jQuery code is very simple...
$(data).find("zimage").each(function() {
alert("node found");
});
That code works, but when I use this...
$(data).find("image").each(function() {
alert("node found");
});
It never finds anything.
Upvotes: 3
Views: 909
Reputation: 95558
What version of jQuery are you using? It appears that jQuery 1.5 has a parseXML()
function:
var data="<aaa><text>bbb</text><image>test</image></aaa>";
var xmlDoc = jQuery.parseXML(data);
var $xmlDoc = jQuery(xmlDoc);
$xmlDoc.find("image").each(function() {
alert("node found"); //this alert pops up because find() returns [image]
});
If you have control over the version of jQuery being used, you can try replacing it with version 1.5, which will give you access to the parseXML()
function. It ooks like this function doesn't do any post-processing to the XML, and so you get a DOM that matches the XML. This way, you also don't need to be aware of what tags get modified, which means less special cases to handle.
Upvotes: 3
Reputation: 2604
You need to convert the xml into a DOM to be traversed by jQuery. jQuery doesn't work on xml directly but does great work through selection on the DOM provided by the browser.
Here is a plugin that returns a DOM for an XML string: http://outwestmedia.com/jquery-plugins/xmldom/
Upvotes: 1
Reputation: 23293
Because javascript is converting your "data" to this:
<aaa><text>bbb</text><img>test</aaa>
Consequently, this works:
var xml = "<aaa><text>bbb</text><image>test</image></aaa>";
var data = $("<div />", { html: xml });
data.find("img").each(function() {
alert("node found");
});
Which is why it is better to use an XML library in almost all cases where you need to parse XML. You never know what quirks will popup.
Upvotes: 1