XML is a lightweight platform independent technology to describe data & HTML is responsible to display data as per the user demand. Let’s take a case where you have your employee’s data in a XML file. During development in a HTML page you want to display details of your employees in html table. Here JavaScript & XMLHttpRequest object comes into picture. Yes using JavaScript we can easily bind data from XML to HTML table.
Look at the below example here I have an xml file “employeeDetails.xml” which contain data related employees. In index.html I want to display these data’s in html table. To do show in index.html I implemented some JavaScript. In side script block first I am creating an object for XMLHttpRequest then using its open method fetching data from the xml file. Then from the response object to get each record I am using getElementsByTagName method. Where tag name is the employeeDetails attribute from XML file. After getting employee details executing a loop to fetch all the records. To create table using document.write method & inside the respective tr & td added XML node values.
xml-to-html-table.htm
<html> <head> <style> table, th, td { border: thin solid gray; padding: 5px; text-align: left; border-collapse: collapse; } </style> </head> <body> <script type="text/javascript"> if (window.XMLHttpRequest) { // for IE7+, Firefox, Google Chrome & Safari xmlhttp=new XMLHttpRequest(); } else { // for IE6, IE5. xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","employeeDetails.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; document.write("<table><tr><th>Name</th><th>Designation</th><th>Salary</th></tr>"); var records=xmlDoc.getElementsByTagName("employee"); for (i=0;i<records.length;i++) { document.write("<tr><td>"); document.write(records[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue); document.write("</td><td>"); document.write(records[i].getElementsByTagName("Designation")[0].childNodes[0].nodeValue); document.write("</td><td>"); document.write(records[i].getElementsByTagName("Salary")[0].childNodes[0].nodeValue); document.write("</td></tr>"); } document.write("</table>"); </script> </body> </html>
employeeDetails.xml
<?xml version="1.0" encoding="UTF-8"?> <company> <employee> <Name>Biswabhusan Panda</Name> <Age>32</Age> <Designation>Sr. Process Lead</Designation> <Salary>56000</Salary> </ employee> < employee> <Name>Shilpa Ghose</Name> <Age>23</Age> <Designation>HRM</Designation> <Salary>26000</Salary> </ employee> < employee> <Name>Jaya Mishra</Name> <Age>35</Age> <Designation>Sr. Technical Lead</Designation> <Salary>76000</Salary> </ employee> </ company >