JavaScript XML to HTML

This page discusses - JavaScript XML to HTML

JavaScript XML to HTML

JavaScript XML to HTML

       

In this section, you will learn how to display the XML data into HTML table.

As you have already learned how to access and manipulate the DOM parser in the previous section. Here we have used the DOM reference to display the data of XML document into html table. For this, we have created  XML document object and allow the DOM parser to load the "data.xml" file. Then we have created an HTML table to display the XML data. The getElementsByTagName() gets all XML Employee nodes and for each Employee node, we display data from the XML elements name and address as table data. 

Following code gets the values from the XML document and display it as the table data:

document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue)

Here is the data.xml file:

<Company>
<Employee>
<name>Tina</name>
<address>Juhu,Mumbai</address>
</Employee>

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

Here is the code:

<html>
<h2>Display XML data in HTML</h2>
<script type="text/javascript">
var xmlDoc=null;
if (window.ActiveXObject){
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation.createDocument){
xmlDoc=document.implementation.createDocument("","",null);
}
else{
alert('Browser cannot handle this script');
}
if (xmlDoc!=null){
xmlDoc.async=false;
xmlDoc.load("data.xml");
document.write("<table border='1'>");
document.write("<tr>");
document.write("<th>");
document.write("NAME"+"<br>");
document.write("</th>");

document.write("<th>");
document.write("ADDRESS"+"<br>");
document.write("</th>");
document.write("</tr>");

var x=xmlDoc.getElementsByTagName("Employee");
for (i=0;i<x.length;i++)

document.write("<tr>");
document.write("<td>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td>");

document.write("<td>");
document.write(x[i].getElementsByTagName("address")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("</tr>");
}
document.write("</table>");
}
</script>
</html>

Output will be displayed as:

Download source Code: