Reading xml file in Javascript

Dear Buddies....


Here I am trying to read a xml file using javascript and displaying it's tag value and attribute values



menux.xml file is as follows....





In javascript the following functions will be using for reading xml file...




var xmlDoc;
var nodedisplay="\n\n";
var idDisplay="\n\n";
var nameDisplay="\n\n";
if (window.ActiveXObject)
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.load("menus.xml")
getValuesie();
}
else if (document.implementation && document.implementation.createDocument)
{
xmlDoc=document.implementation.createDocument("","",null);
}
function getValuesie()
{
nodes=xmlDoc.documentElement.childNodes
for(var i=0;i {
nodedisplay=nodedisplay+nodes.item(i).text+"\n";
idDisplay=idDisplay+nodes.item(i).getAttribute('id')+"\n";
nameDisplay=nameDisplay+nodes.item(i).getAttribute('name')+"\n";
}
nodeValue.innerText=nodedisplay;
idValue.innerText=idDisplay;
nameValue.innerText=nameDisplay;
}
function afor()
{
if (document.implementation && document.implementation.createDocument)
{
xmlDoc.async=false;
var isLoaded = xmlDoc.load("menus.xml");
if (isLoaded == true)
{
length=xmlDoc.getElementsByTagName("menu").length;
for(var i=0;i {
nodedisplay = nodedisplay + xmlDoc.getElementsByTagName("menu")[i].childNodes[0].nodeValue+"\n";
}
return nodedisplay;
}

}
}

function bfor()
{
if (document.implementation && document.implementation.createDocument)
{
xmlDoc.async=false;
var isLoaded = xmlDoc.load("menus.xml");
if (isLoaded == true)
{
length=xmlDoc.getElementsByTagName("menu").length;
for(var i=0;i {
idDisplay = idDisplay + xmlDoc.getElementsByTagName("menu")[i].getAttribute("id")+"\n";
}
return idDisplay;
}
}
}
function cfor()
{
if (document.implementation && document.implementation.createDocument)
{
var c="\n\n";
xmlDoc.async=false;
var isLoaded = xmlDoc.load("menus.xml");
if (isLoaded == true)
{
length=xmlDoc.getElementsByTagName("menu").length;
for(var i=0;i {
nameDisplay = nameDisplay + xmlDoc.getElementsByTagName("menu")[i].getAttribute("name")+"\n";
}
return nameDisplay;
}
}
}


In the body ....there are three span's with ids....in each span ...after the span tag closed in script, write the following code...




In first span with Id of "nodeValue"


if (document.implementation && document.implementation.createDocument)
{
document.getElementById("nodeValue").innerHTML=afor();
}

next span with the Id of "idValue"


if (document.implementation && document.implementation.createDocument)
{
document.getElementById("idValue").innerHTML=bfor();
}

last span with the Id of "nameValue"


if (document.implementation && document.implementation.createDocument)
{
document.getElementById("nameValue").innerHTML=cfor();
}

3 comments:

Raja said...

Thanks! your code helped me lot.

SaravananJ said...

Hey, Vinoth... it looks fantastic man...

SaravananJ said...
This comment has been removed by the author.