xml load and parse from javascript

I needed to load and parse some opml in a javascript: any recent browser (aka Mozilla, Firefox or IE6) has the abilty to asyncronously load a resource from the net (all the AJAX stuff is based on this), moreover of this is an xml file it is possible to have it parsed into a DOM object.
But the browsers i tested don’t parse correctly the content returned from the server if it cannot be identified as xml from the MIME type (or the extension). This can be a problem if you cannot set the mime type returned form the server (e.g. is someone elses’ server) and the extension is not .xml (in my case it is .opml).
A search on google didn’t come up with a solution, so here it is how i did it:

function parse(text) {
	var doc;
	if (typeof DOMParser != 'undefined') {
		var parser = new DOMParser();
		doc = parser.parseFromString(text, "text/xml");
	}
	else if (typeof ActiveXObject != 'undefined') {
		doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(text);
	}
	return doc;
}
function load (url, callback) {
	var httpRequest;
	if (typeof XMLHttpRequest != 'undefined') {
		httpRequest = new XMLHttpRequest();
	}
	else if (typeof ActiveXObject != 'undefined') {
		httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
	}
	if (httpRequest) {
		httpRequest.open('GET', url, true);
		httpRequest.onreadystatechange = function () {
			if (httpRequest.readyState == 4 &&
				httpRequest.status == 200) {
				callback(httpRequest.responseText);

			}
		};
		httpRequest.send(null);
	}
}

I did separate the loading and parsing phases, and using DOMParser for Mozilla/Firefox and XMLDOM for IE, passing them the xmlText. This has been tested with Firefox and InternetExplorer 6

 
 

Comments are closed.