Parsing responseXML with Prototype's $()
-
22-09-2019 - |
Question
I've got XML coming back from an Ajax.Request
in Ajax.Response.responseXML
. My XML actually contains XHTML tags which I hope to append into my document.
I'm having issues appending nodes from the responseXML
into the current document, however. I suspect that this is because they are XML nodes and not DOM nodes.
Wrapping the responseXML
in $()
doesn't seem to return an extended version of the nodes, either, and the documentation doesn't say that it will or won't.
Does Prototype provide a way to make use of the responseXML
, and if not, is there a cross-browser way to parse the response and use it?
Solution
No prototype does not have a native way to parse XML. Nor can you extend the xml with $(xml) and then walk the DOM with .next(),.select(), etc.
Here is an example of what I did recently on a project to manually parse some XML from spell check results. Should get you started.
parseResults: function(results) {
var c = results.responseXML.getElementsByTagName('c');
var corrections = $A(c);
if(!corrections.size()){
this.link.insert({ after: '<span class="spellCheckNoErrors">No spelling errors</span>' });
(function(){ this.link.next().remove(); }.bind(this)).delay(1);
return null;
}
this.res = $A();
corrections.each(function(node){
sugg = node.childNodes[0].nodeValue;
offset = node.attributes[0].nodeValue;
len = node.attributes[1].nodeValue;
this.res.push(
$H({
word: this.text.substr(offset, len),
suggestions: sugg.split(/\s/)
})
);
},this);
this.overlay();
},
OTHER TIPS
Although I accepted Christian's answer as the "correct" answer, a colleage of mine showed me a way to parse an XML response with Prototype.
Rather that using responseXML
, you simply create an Element
and then update()
it with the responseText
. You can then use select()
and methods like it to traverse the nodes.