Friday, 19 April 2013

Parsing XML with JQuery

To parse an XML file with JQuery, you can follow these simple steps.

1. Obtain the xml using JQuery Ajax. There are two possible location where the xml file can be located. You have to make sure of your file path.
2. Parse the Ajax Response (your XML file) and append the data to your html code.

Suppose you have a XML file: (download here)

<student_list>
   <students>
     <student_id>2013001</student_id>
       <name>Clare Marie Ciriaco</name>
    </students>
    <students>
      <student_id>2013002</student_id>
        <name>Jane Doe</name>
   </students>
   <students>
     <student_id>2013003</student_id>
       <name>John Fitzgerald</name>
   </students>
</student_list>

To parse it,

<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function(){
$("#studentTable").hide();
$.ajax({
//This is the URL of my XML FILE
url:"https://dl.dropboxusercontent.com/u/25566095/student_xmllist.xml",
//Indicates the type of file
dataType:"xml",
success: function(response){
var rowCounter=0;
$("#studentTable").show();
$(response).find('students').each(function(){
var newsId = $(this).find('student_id').text();
var headline = $(this).find('name').text();
//APPEND THE DATA by row
$("#studentTable").append("<tr id=row" + rowCounter + "><td id=news" + rowCounter + ">" + $(this).find('student_id').text() + "</td>");
$("#row" + rowCounter).append("<td id=name" + rowCounter + ">" +$(this).find('name').text() + "</td></tr>");
rowCounter++;
});
},
error: function(e){
alert(e);
}
});
});
</script>
</head>
<body>
Data from <i>XML FILE</i>
<table id="studentTable" border="1">
<tr id="titleRow">
<td id="studentId">Student Id</td><td id="studentName">Student Name</td>
</tr>
</table>
</body>
</html>

OUTPUT:




0 comments:

Post a Comment