Parse XML with JavaScript

Free HTML5 Game Tutorial for Beginners: Page 19

Overview Load the XML Parse the XML Show Data from XML Browser Differences Summary
Parse XML with JavaScript Icon

Overview

This tutorial explains how to load, parse, and access elements of an XML file with JavaScript. This tutorial demonstrates some workarounds to load and parse XML files with different browsers. For example some browsers load XML with window.XMLHttpRequest while others load XML with ActiveXObject.

The example Surface Game loads one XML file for each level. XML files store data representing a set of questions, a set of answers, and a set of image source file names. The XML files are part the of model component of the Model View Controller (MVC) design pattern.

For details regarding how to make an XML file see the Create an XML File tutorial.

Parse

In computer science the term parse means to divide a text file into separate components. This tutorial explains how to extract questions, answers, and image file names from an XML file.

Load the XML File

The function loadXML(lvl) listed below, loads one XML file. lvl is a Number representing the current level of the game. loadXML(lvl) returns an XML DOM object to the controller. sPath in the code below, is a String representing the path to the directory where the XML files are stored.

Currently loadXML(lvl) waits until the file downloads. When a function waits the player waits too. For better performance download the XML file with an asynchronous event handler. Asynchronous events process outside of the current thread. The current thread can process other events while the player waits. When prepared correctly, events on the current thread can involve or distract the player.

For asynchronous event handling assign a unique function to process the XML file after it downloads. However this simplified game example calls loadXML(lvl) synchronously.

The following listing demonstrates how to download an XML file from the server. Variable sPath is a string with the path to the XML file. Variable lvl is an integer representing the current level. The XML files for two levels are named 1.xml or 2.xml.

First prepare an XML request. Second send the request to the server, with the file name and file path. Function loadXML() returns an XML DOM variable which function loadQuestions() processes next.

function loadXML(lvl){ 

var sFile = sPath+lvl.toString()+".xml";

var xd	= null;

if (window.XMLHttpRequest)
{

// IE, Firefox, Chrome, 
// Opera, Safari
xmlhttp=new XMLHttpRequest();

}

else
{

// Use for IE below version 7.
xmlhttp=new ActiveXObject
(
"Microsoft.XMLHTTP"
);
}

...

xmlhttp.open
(
"GET",
sFile,
false
);
	
xmlhttp.send();
	
xd=xmlhttp.responseXML;

...

return xd;

}

Parse the XML

A set of questions, answers, and Image file names are retrieved from an XML DOM variable named xmlDoc. Function loadQuestions() listed below, copies a list of questions to variable xQuestions, a list of answers to variable xAnswers, and a list of Image file names to variable xGraphics.

The API function getElementsByTagName() returns a NodeList of elements with the tag name provided as a parameter. Previous lessons described preparing the tag names and values. The tag names were declared with DTD. The tag values were saved to an XML File.

function loadQuestions(){	

var xmlDoc = loadXML(nLevel);

if (xmlDoc != null)
{

xQuestions = xmlDoc.getElementsByTagName
(
"q"
);
 
xAnswers = xmlDoc.getElementsByTagName
(
"a"
);
 
xGraphics = xmlDoc.getElementsByTagName
(
"g"
);
 
showQuestion();
 
}

}

Show Data from XML

Function showQuestion(), listed below, accesses the textContent property if it's available. Otherwise showQuestion() accesses the text property. Function showQuestion() retrieves of one element within each NodeList. The NodeLists include xGraphics, xQuestions and xAnswers. The NodeLists were retrieved from XML in the Parse the XML section above.

showQuestion() calls functions which expect one String parameter. Functions viewImage() and viewText() display the image path and text passed through their parameter list. The answer to the current question is saved in the String named sCorrect.

function showQuestion(){
...
	
// For Safari, FireFox, Chrome, etc.
if (xGraphics[nIndex].textContent != null){
	
viewImage(
 xGraphics[nIndex].textContent
);
		
viewText(
 xQuestions[nIndex].textContent + sOutput,
 false
);

sCorrect = xAnswers[nIndex].textContent;

}
	
// For IE 9 etc.
else {
 viewImage(
  xGraphics[nIndex].text
 );
 
viewText(
 xQuestions[nIndex].text + sOutput,
 false
);
		
sCorrect = xAnswers[nIndex].text;
}

...	

}

Browser Differences

The previous listing Show Data from XML, demonstrated that textContent is not currently implemented consistently for all browsers. The Load the XML File section also demonstrated window.XMLHttpRequest isn't used consistently across browsers either.

Test the textContent property for null, before attempting to use it. If textContent is null, then use the text property. Test window.XMLHttpRequest for null as well. If window.XMLHttpRequest is null, then create a new ActiveXObject.

Summary

This tutorial explained how to load, parse, and access elements of an XML file with JavaScript. This tutorial demonstrated some workarounds to load and parse XML files with different browsers. For example some browsers load XML with window.XMLHttpRequest while others load XML with ActiveXObject.

The example Surface Game loads one XML file for each level. XML files store data representing a set of questions, a set of answers, and a set of image source file names. The XML files are part the of model component of the Model View Controller (MVC) design pattern.

For details regarding how to make an XML file see the Create an XML File tutorial.

Improved Performance

For better performance, download the XML file with an asynchronous event handler. Asynchronous events process outside of the current thread. In other words assign a unique function to process the XML file after it downloads. This tutorial explains how to download and parse synchronous XML files. Synchronous processing waits until an action completes, before executing the next procedure.

For the next tutorial, tap the image icon containing text which says Next Lesson, or the right pointing arrow at the bottom of the page.

Previous Page Next Page
Copyright © 2015 Seven Thunder Software. All Rights Reserved.