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
</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!

Advertisements

3 Comments

Filed under AJAX, javascript

3 responses to “Inline/Embedded XML in HTML

  1. Simon

    Thanks for your sharing, I have tried but have some problems.
    1. style=’display:none;’ only works if I add a tag before the XML tag, if I put it inside tag. It does not work. It still display.
    2. The Javascript is not working on Firefox.
    Maybe because I am not too familiar with it. Would you mind making some worked examples?
    In my case, my goal is to create a html include a xml data file to form a table as a result.
    Because XML Data Island only work in IE, so I try some other workaround. I have tried this:
    http://www-128.ibm.com/developerworks/web/library/wa-ie2mozgd/
    But I still cannot get the result.

    Thanks a lot!

  2. hey
    can i create any xml file inside HTML using ……… .
    Please reply

  3. Please i want to embed just a Part from a webpage with the XML ..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s