Daily Archives: October 24, 2007

Inline/Embedded XML in HTML

Ajax is cool, but in scenarios where it’s not needed, there is no need to use it. For example, if there is some XML data that is being rendered on the UI using Javascript, if the XML data is static, then there is no need to first load the page and then use the XMLHTTPRequest object (or Prototype.js) to get the XML and then use it.

Instead, it’s possible to simply embed the XML into the HTML document itself. What’s the benefit of this? It simply avoids an extra round-trip to the server. However, doing this required a bit of research and the typical differences with Firefox and IE. So, here is what I had researched and did to make it work in both cases.

IE supports xml tag that can be used to embed XML into a HTML page. In Firefox, simply embed the entire content in the same xml tag. However, an extra piece of code is needed to make it work in Firefox.

The syntax is

<xml id='xmldata' style='display:none;'>
any piece of xml

The style=’display:none’ is needed in Firefox. Otherwise, any content within this tag is going to be displayed. Finally, in the code following javascript is required

var xml = document.getElementById(‘xmldata’);
if(xml.documentElement == null)
xml.documentElement = xml.firstChild; /* This is required for Firefox. Make sure there is no gap between the xml tag and the root node */

That’s it!


Filed under AJAX, javascript