In the Decoding jQuery series, we will break down every single method in jQuery, to study the beauty of the framework, as an appreciation to the collective/creative geniuses behind it.
jQuery.parseXML()
jQuery.parseXML uses the native parsing function of the browser to create a valid XML Document.
An example usage is:
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>", xmlDoc = $.parseXML( xml ), $xml = $( xmlDoc ), $title = $xml.find("title"); console.log($title.text( "XML Title" )); // return "XML Title"
Let’s take a look at the source to see how it actually works:
parseXML: function(data, xml, tmp) { if (window.DOMParser) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString(data, "text/xml"); } else { // IE xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = "false"; xml.loadXML(data); } tmp = xml.documentElement; if (!tmp || !tmp.nodeName || tmp.nodeName === "parsererror") { jQuery.error("Invalid XML: " + data); } return xml; }
DOMParser is available to web pages, but it’s not part of any standard and is not supported by some browsers, guess what that some browser is? Yea, IE… Unfortunately, Internet Explorer does not support it. So if window.DOMParser returns false, we will use ActiveXObject("Microsoft.XMLDOM") instead. (Edit: from IE9 onwards, window.DOMParser is recognized)
Note, this method is used to parse strings and streams of XML text, if you want to parse XML received from the server, you can just use the responseXML property of XMLHttpRequest for which we will introduce in a different jQuery method.
Reference:
jQuery source on github: https://github.com/jquery/jquery/blob/master/src/core.js#L555
DOMParser under MDN Docs: https://developer.mozilla.org/en/DOMParser
Van Steenbeek’s article: https://sites.google.com/a/van-steenbeek.net/archive/explorer_domparser_parsefromstring




DOMParser is available now in IE9!
Pingback: Apprendre jQuery
FYI
I think there is a typo one your example one
“XML Title” should be “RRS Title”