DOMParser for IE and Safari
A few days ago Dave over at the WebGraphics blog posted about how to parse a string into a DOM tree for Safari.
I commented “How about implementing the DOMParser object in js?” and before I knew it I did it myself and adding IE compatibility on the way:
if (typeof DOMParser == "undefined") {
DOMParser = function () {}
DOMParser.prototype.parseFromString = function (str, contentType) {
if (typeof ActiveXObject != "undefined") {
var d = new ActiveXObject("MSXML.DomDocument");
d.loadXML(str);
return d;
} else if (typeof XMLHttpRequest != "undefined") {
var req = new XMLHttpRequest;
req.open("GET", "data:" + (contentType || "application/xml") +
";charset=utf-8," + encodeURIComponent(str), false);
if (req.overrideMimeType) {
req.overrideMimeType(contentType);
}
req.send(null);
return req.responseXML;
}
}
}
Both Opera and Mozilla already have this object
July 14th, 2005 at 19:04
Very useful. Only recommendation is to change the PROGID value for IE. Seems “Msxml2.DOMDocument” is the best bet as it will always get the most recent version (
July 14th, 2005 at 19:05
up until v4.0.
Burst has some nice documenation about this
http://burstproject.org/build/apidoc/html/classburst_1_1xml_1_1XmlDoc.html
sorry about the double post.
July 14th, 2005 at 19:27
Thanks for the link. The only reason I can see for not using IXMLDOMDocument is that one might want to use XPath and then IXMLDOMDocument2 must be used.
July 24th, 2005 at 8:35
It’s been added to recent Safari 2.0 seeds.
July 24th, 2005 at 23:24
Yeah, I saw that when browsing their source code
August 15th, 2005 at 12:20
I used the code above but I could only get error code: No such interface supported… but when I tried to print out the nodes the structure of the returned object seems to be well constructed.
Please advise
August 29th, 2006 at 0:04
Would you mind tell me which editor you are using for javascript file?
July 26th, 2007 at 20:35
Shouldn’t the line:
if (req.overrideMimeType) { req.overrideMimeType(contentType); }
be instead:
if (contentType && req.overrideMimeType) { req.overrideMimeType(contentType); }
as the lines above treat contentType as an optional argument?