Wednesday, November 26, 2008

Reading Xml file using javascript

Xml is very important in things like especially communication between various applications which are built in different plat forms or technologies.

We can say simply in a word xml is mediator or a channel between applications to talk to each other.

So to read or write xml we have parsers in frame work library classes built by each technology of its own. Where as the xml format or way of handling data in it is always optimized and same.

For example to read xml file through java script Microsoft has provided an activex object "Microsoft.XMLDOM". So creating an instance to this can be used to load an xml file and read the file.
Ex:-
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async=false; //says to load the file and read asynchornously
xmlDoc.load(xml filepath);


In this way we can load an xml file through browser.
A small example below shows how to read data from xml file and display in browser.


Demo Example:-
I create a xml file named as Demo.xml file which has information about strength of each class in different schools.

<?xml version="1.0" encoding="utf-8" ?>
<Schools>
<School SchoolName="Sikile school">
<Classes>
<Class Class="1" Strength="39"></Class>
<Class Class="2" Strength="40"></Class>
<Class Class="3" Strength="50"></Class>
</Classes>
</School>
<School SchoolName="Bharatiya vidhya bhavan">
<Classes>
<Class Class="1" Strength="59"></Class>
<Class Class="2" Strength="70"></Class>
<Class Class="3" Strength="80"></Class>
</Classes>
</School>
</Schools>










I am creating an html page say Demo.htm which should read this xml file and display information accordingly.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Demo</title>
<script type="text/javascript" language="javascript">
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
var Types=new Array();
function affiliate(){
div_xml.innerHTML='Loading...';
xmlDoc.load("Demo.xml");
Load("Demo.xml")
}
var htm;
function Load(SV){ Root=xmlDoc.documentElement;

htm="<blockquote>The file: "
htm+="<a href='"+SV+"'>"+SV+"</a><br></blockquote>";
htm+="<table rules='rows'>";
WriteChildNodes(Root);
htm+="</table>";
div_xml.innerHTML=htm;
}

function WriteChildNodes(rt)
{
htm+="<tr>";
if(rt.attributes!=null)
{
for(var j=0;j<rt.attributes.length;j++)
{
htm+="<td width=100>"+rt.attributes[j].nodeName+"</td>";
htm+="<td width=100>"+rt.attributes[j].nodeValue+"</td>";
}
}
if(rt.childNodes!=null)
{
for(var i=0;i<rt.childNodes.length;i++)
{
WriteChildNodes(rt.childNodes[i]);
}
}
htm+="</tr>";
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input type="button" value="Read Xml" id="btnReadXml" onclick="affiliate();"/>
<div id="div_xml"></div>
</td>
</tr>
</table>
</body>
</html>






Input :




Output:




No comments: