There doesn't seem to be any useful documentation out there about parsing XML in Mootools. Either it's so stupidly easy nobody could be bothered to mention it, or it's so fiendishly difficult everybody's given up trying. Does anyone have any simple cross browser method for parsing XML with Mootools?
Here's my little XML file data.xml:
<?xml version="1.0"?>
<suggestions>
<suggestion winning="Y">
<copy><![CDATA[Draw straws to see who wins]]>
</copy>
<person><![CDATA[Sue]]>
</person>
<location><![CDATA[London]]>
</location>
</suggestion>
<suggestion winning="N">
<copy><![CDATA[Race your friends round the meeting room]]>
</copy>
<person><![CDATA[Jack]]>
</person>
<location><![CDATA[Lancaster]]>
</location>
</suggestion>
</suggestions>
And this is my JS:
window.addEvent('domready', function(){
var outputHTML = '';
var req = new Request({
url: 'data.xml',
method: 'get',
onSuccess: function(responseText, responseXML) {
if(typeOf(responseXML) != 'document'){
responseXML = responseXML.documentElement;
}
var suggestions = responseXML.getElements('suggestion');
suggestions.each(function(item) {
outputHTML += '<p>';
outputHTML += item.getElement('copy').get('text') + '<br/>';
outputHTML += '<b>' + item.getElement('person').get('text') + '</b>: ';
outputHTML += item.getElement('location').get('text') + '<br/>';
if (item.get('winning') == 'Y') {
outputHTML += ' <b>Won!</b>';
}
outputHTML += '</p>';
});
$('output').set('html', outputHTML);
}
}).send();
});
I found I had to do the responseXML = responseXML.documentElement
bit to make it work in Chrome. This JS works OK in Chrome and FF, but IE complains "Object doesn't support this property or method" for line 16, where I'm trying to run getElements('suggestion') on responseXML.
Can any kindly expert restore my faith in the mystical powers of Mootools?
Cheers Fred
This is a rather old question but I recently had the same problem, so I'd like to share my solution.
The
responseXML
variable you receive fromRequest
is simply the unaltered XML response from your browser. Under IE (up to version 9), you'll receive an IXMLDOMDocument object. I found that the easiest way to convert this object to a MooToolsElement
tree is the following:Alternatively, you can use IE's
DOMParser
which might be more efficient:In MooTools Forge there is a plugin for converting XML to a JavaScript object:
http://mootools.net/forge/p/xml2js_converter