Home Javascript Javascriptexamples JavaScript XML Parser



JavaScript XML Parser
Posted on: April 18, 2011 at 12:00 AM
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:

 

       

Related Tags for JavaScript XML Parser:


More Tutorials from this section

Ask Questions?    Discuss: JavaScript XML Parser  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.