Transform XML content into JavaScript XML DOM object and display the values in a table



My code is not working and i'm not able to figure out why. I'm trying to display only firstname,lastname and contactNo.


Here's the codes from the xml file:



<?xml version="1.0"?>
<Company>
<Employee category="technical">
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
</Employee>
<Employee category="non-technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
</Employee>
</Company>


The html file:



<!DOCTYPE html>
<html>
<body>
<div id="xml_ajax"> </div>

<script>

if(window.XMLHttpRequest)
{
var xmlhttp = new XMLHttpRequest();
}
else
{
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET","trying.xml",false);
xmlhttp.send();

xmlDoc = xmlhttp.responseXML; //returns content as XML DOM

var html_table = '<table border="1"><tr><th>FirstName</th><th>LastName</th><th>ContactNo</th> </tr>';

var array_employee = xmlDoc.getElementsByTagName("Employee");

for(i=0; i<array_employee.length; i++)
{
var employee_cat = array_employee[i].getAttribute('category');

var array_firstname = array_employee[i].getElementsByTagName("FirstName")[0].childNodes[0].nodeValue;

var array_lastname = array_employee[i].getElementsByTagName("LastName")[0].childNodes[0].nodeValue;

var array_contactNo = array_employee[i].getElementsBytagName("ContactNo")[0].childNodes[0].nodeValue;

html_table += '<tr><td>'+array_firstname+'</td><td>'+array_lastname+'</td> <td>'+array_contactNo+'</td></tr>';

}

html_table+='</table>';

document.getElementById('xml_ajax').innerHTML = html_table;
</script>
</body>
</html>


Your help would be much appreciated. Thanks.


No comments:

Post a Comment