Tuesday, October 9, 2012

Parse XML file in JavaScript

As one of reader asked about how to handle XML respone if we get more than records or if your XML file have many child nodes.
I gave here one complete example with XML file and JavaScript in JSP.

1. abc.xml
<Students>
<Student>
<Name>Binod Kumar Suman</Name>
<Hostel>Ganga</Hostel>
<Contact>999999999</Contact>
</Student>

<Student> <Name>Pramod Kumar Modi</Name>
<Hostel>Godawari</Hostel>
<Contact>88888888</Contact>
</Student>

<Student>
<Name>Sanjay Kumar</Name>
<Hostel>Satjal</Hostel>
<Contact>7777777</Contact>
</Student>

<Student>
<Name>Mukesh Ambani</Name>
<Hostel>Rewti</Hostel>
<Contact>6666666</Contact>
</Student>

</Students>

2. StudentInfo.jsp
<html><head><title>Binod Java Solution AJAX </title>
<script type="text/javascript">

function showResult(){

var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false"; xmlDoc.load("abc.xml");
var students=xmlDoc.documentElement;
var student = students.childNodes(0);
var rows = students.childNodes.length; v
ar cols = student.childNodes.length;

var body = document.getElementsByTagName("body")[0];
//var tabl = document.createElement("table");
var tabl = document.getElementById("studentinfo");
var tblBody = document.createElement("tbody");

for (var i = 0; i < rows; i++) {
var row = document.createElement("tr");
student = students.childNodes(i);

for (var j = 0; j < cols; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode(student.childNodes(j).firstChild.text); cell.appendChild(cellText);
row.appendChild(cell);
}

tblBody.appendChild(row);
tabl.appendChild(tblBody);
tabl.setAttribute("border", "2");
}

</script>

</head><body onload="showResult()">
<h2> GET STUDENT INFO </h2><br>

<table id="studentinfo"> <tr bgcolor='red'> <td >Name</td><td>Hostel</td><td>Contact</td> </tr> </table>
</body>
</html>

0 comments:

Post a Comment