A little known but cool feature of Internet Explorer is its support for XML data islands. Basically, you can embed some XML data in a page like this:
<html>
 <head>
  <xml>
   <root>Some dataroot>
  xml>
 head>
Even cooler, you can reference an external data source:
<xml src="data.xml">xml>

The classic “Ajax” way to load XML data involves a couple of ActiveX objects:
var http = new ActiveXObject("Microsoft.XMLHTTP");
http.open("GET", "data.xml", false);
http.send(null);
var xmlDocument = http.responseXML;
responseXML is a tricky beast, on most platforms it refers to an XML document. This means you can do things like access the root node through the documentElement property. Unfortunately this does not work on Internet Explorer:
alert(xmlDocument.documentElement);
// ==> [object Element] for Mozilla
// ==> null             for Internet Explorer 
To create a true XML document for Internet Explorer you must use the responseText property and another ActiveX object to parse it:
var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
xmlDocument.loadXML(http.responseText);
An easier way to achieve the same result without ActiveX is this:
var xml = document.createElement("xml");
xml.src = "data.xml";
document.body.appendChild(xml);
var xmlDocument = xml.XMLDocument;
document.body.removeChild(xml);
The code above will load and parse an external XML file. The resulting object is a true XMLresponseXML returned by the XMLHttpRequest document which can be treated the same as the object on other platforms.
The above code will only work on a local file system. When dealing with remote data you check the readyState property to ensure that the data has been fully loaded. You can also trap the onreadystatechange event as you would for the XMLHttpRequest object.



This entry was posted on 7:57 AM and is filed under , , . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

0 comments: