Home blog programming Retrieve and parse XML data using JavaScript

Retrieve and parse XML data using JavaScript

Posted on March 17, 2014 by Edit

Program to fetch XML. And Sample code to demonstrate the process of parsing the XML data. Also look out for demo at bottom of this page.


/* Function to fetch XML at given path */
function loadXML(xmlpath) {
	var xmlhttp;
	var xmlDoc;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.open("GET", xmlpath, false);
	xmlDoc = xmlhttp.responseXML;
	return xmlDoc;

Sample XML parsing implemetaion

XML File

<?xml version="1.0" encoding="UTF-8"?>
  <student id="100026">
    <name>Joe Average</name>
      <result course="Math 101" grade="C-"/>
      <result course="Biology 101" grade="C+"/>
      <result course="Statistics 101" grade="D"/>
  <student id="100078">
    <name>Jack Doe</name>
    <major>XML Science</major>
      <result course="Math 101" grade="A"/>
      <result course="XML 101" grade="A-"/>
      <result course="Physics 101" grade="B+"/>
      <result course="XML 102" grade="A"/>

JS Code

/* Sample code to fecth and parse below XML. */

xml = loadXML("/assets/xml/students.xml");

function parseXML(xml) {
        console.log('ID: '+$(this).attr('id'));
        console.log('Name: '+$(this).find('name').text());
        console.log('Age: '+$(this).find('age').text());
               console.log('Major: '+$(this).text());
                console.log('Result:\n\t Course: '+$(this).attr('course')+'\n\t Grade: '+$(this).attr('grade'));


Fetch Click here to fetch XML

Tags :
This website is made possible by displaying online advertisements to our visitors.
Please consider supporting by disabling your ad blocker.

Get new posts by email:
loading comments...
© 2022 Shivaji Varma. Made in India.