Articles → Jquery → Reading An Xml File Using Jquery
Reading An Xml File Using Jquery
Sample XML File
<?xml version="1.0" encoding="utf-8" ?>
<RecentSessions>
<Session>
<Title>Session for .Net</Title>
<Location>New Delhi</Location>
<Date>12/1/2010</Date>
</Session>
<Session>
<Title>Session for Cloud Computing</Title>
<Location>Mumbai</Location>
<Date>4/1/2010</Date>
</Session>
<Session>
<Title>jQuery Techniques</Title>
<Location>Chandigarh</Location>
<Date>6/2/2010</Date>
</Session>
<Session>
<Title>MySQL Database Session</Title>
<Location>Banglore</Location>
<Date>14/2/2010</Date>
</Session>
</RecentSessions>
Syntax
$.ajax({
type: "[HTTP request method]",
url: "[URL of xml file]",
dataType: "[data type]",
success: "[Method to parse]"
});
- URL → The path of the XML file on which the request is sent to fetch the data
- data type → The data type of the output
- success → Method which executes when the call to the server is successful i.e., when the response comes from the server
- method to parse → The method to be executed when the Ajax call is successful
Reading The XML File
$(document).ready(
function() {
$.ajax({
type: "GET",
url: "./SessionInfo.xml",
dataType: "xml",
success: function(xml) {
$(xml).find("Session").each(function() {
$("#xmlData").append(" <
br / > " + $(this).find("
Title ").text());
}
);
}
});
});
Output
Click to Enlarge
Code
<?xml version="1.0" encoding="utf-8" ?>
<RecentSessions>
<Session>
<Title>Session for .Net</Title>
<Location>New Delhi</Location>
<Date>12/1/2010</Date>
</Session>
<Session>
<Title>Session for Cloud Computing</Title>
<Location>Mumbai</Location>
<Date>4/1/2010</Date>
</Session>
<Session>
<Title>jQuery Techniques</Title>
<Location>Chandigarh</Location>
<Date>6/2/2010</Date>
</Session>
<Session>
<Title>MySQL Database Session</Title>
<Location>Banglore</Location>
<Date>14/2/2010</Date>
</Session>
</RecentSessions>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title></title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "./SessionInfo.xml",
dataType: "xml",
success: function(xml) {
$(xml).find("Session").each(function() {
$("#xmlData").append(" < br / > " + $(this).find("
Title ").text());
});
}
});
});
</script>
</head>
<body>
<form id="form1">
<div id="divData">
<b>Numbers of Sessions</b>
<div id="xmlData"></div>
</div>
</form>
</body>
</html>