Retrieve and parse XML data using JavaScript

Posted on March 17, 2014 by

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.

Code

/* 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);
	xmlhttp.send();
	xmlDoc = xmlhttp.responseXML;
	return xmlDoc;
}

Sample XML parsing implemetaion

XML File

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

JS Code

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

xml = loadXML("/assets/xml/students.xml");
$(document).ready(funtion(){
	parseXML(xml);
});

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

Demo

Fetch Click here to fetch XML

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