Monday, November 9, 2009

Read XML File from Javascript

For reading xml data using javascript we need to go to the following steps.
1. First create xml file File name called book.xml or anything else.
2. on the another file write the below code
============================book.xml=============================================
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
==================================================
================Page where want to display the xml data =============================
<head>
<script type="text/javascript">
function loadXmlData(FName)
{
try{ // Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}
catch(e){
try{ // Mozila,Safari,Opera,etc
xmlDoc = document.implementation.createDocument("","",null);
}
catch(e){alert(e.message);}
}

try{
xmlDoc.async = false;
xmlDoc.load(FName);
return xmlDoc;
}
catch(e){alert(e.message);}
}

function get_firstChild(n)
{
y=n.firstChild;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}
</script>
</head>

<body>
<script type="text/javascript">
xmlDoc=loadXmlData("books.xml");
var Count = xmlDoc.getElementsByTagName("title");
//alert(Count.length);
for(var z=0;z<Count.length-1;z++)
{
document.write(z+1+" "+Count[z].childNodes[0].nodeValue +"<br/>");
}


document.write("<hr/>");
document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);

x=get_firstChild(xmlDoc.getElementsByTagName("book")[3]);
document.write(x.nodeName);
</script>
</body>

==================Output=====================
1 Everyday Italian
2 Harry Potter
3 XQuery Kick Start
<hr/>
Everyday Italian
Giada De Laurentiis
2005title

No comments:

Post a Comment