Home Javascript Javascriptexamples JavaScript XML Parser
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

JavaScript XML Parser

Advertisement
This page discusses - JavaScript XML Parser

JavaScript XML Parser

       

In this section, you will learn how to access and manipulate XML document using DOM parser in javascript.

XML parser reads and loads the xml into computer memory and converts it into DOM object. After loading the document, the data can be manipulated using DOM  with JavaScript. Now the text and their values can be updated, deleted. New elements can also be created using DOM.

In the given example we used the DOM reference to get the values from the elements of XML document. The ActiveXObject("Microsoft.XMLDOM") creates the Microsoft XML document object for Internet Explorer and document.implementation.createDocument("","",null) creates XML document object for other browsers. xmlDoc.async=false indicates that the parser continues the script execution after loading of the document fully. The method xmlDoc.load("data.xml") allows the parser to load an XML document 'data.xml'. The childNodes[0].nodeValue gets the value of the node from the element.

Here is the data.xml:

<Company>
<Employee>
<name>Angelina</name>
<address>Rohini,Delhi</address>
<designition>Engineer</designition>
</Employee>
</Company>

Here is the code:

<html>
<h2>XML Parser</h2>
<script type="text/javascript">
function parseXML(){
try {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(ex){
try {
xmlDoc=document.implementation.createDocument("","",null);
}
catch(ex){
alert(ex.message);
return;
}
}
xmlDoc.async=false;
xmlDoc.load("data.xml");
document.getElementById("n1").innerHTML=xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("n2").innerHTML=xmlDoc.getElementsByTagName("address")[0].childNodes[0].nodeValue;
document.getElementById("n3").innerHTML=xmlDoc.getElementsByTagName("designition")[0].childNodes[0].nodeValue;
}
</script>
</head>
<body onload="parseXML()">
<h3>Employee's Information</h3>
<b>Name:</b> <span id="n1"></span><br>
<b>Address:</b> <span id="n2"></span><br>
<b>Designition:</b> <span id="n3"></span>
</body>
</html>

Output will be displayed as:

Download Source Code:

 

       

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Ask Questions?    Discuss: JavaScript XML Parser  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Can ┼?ahin Bak─▒r
October 26, 2011
thanks

thanks for sharing
Devik
December 10, 2012
Doesn't work in Chrome

Hi, Thanks for the tutorial. The given example works perfect in IE and Firefox; however, doesn't work in chrome. Thanks.
DMCA.com