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.

Often the current thread equals the user interface thread where text fields, graphics, and animation display. When prepared correctly, events on the current thread can entertain the player. For example the current thread might explain how to play the game, show an interesting animation, or play music.

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 and 2.xml. Load just one XML file at a time, based on the current level.

First prepare an XML request with either xmlhttp = new XMLHttpRequest() or xmlhttp = new ActiveXObject{"Microsoft.XMLHTTP"). Second request to Get the file, with the file name and request, as follows.

xmlhttp.open("GET",sFile,false);

Third send the request to the server as follows.

xmlhttp.send();

Fourth retrieve a reference to an XML DOM object as follows. Variable xd is simply a document type.

xd = xmlhttp.responseXML;

Last loadXML() returns an XML DOM reference to the calling function.

The entire loadXML() function follows.

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

Function loadQuestions() calls the function we just covered named, loadXML(). The return document reference is saved to local variable xmlDoc.

A set of questions, answers, and Image file names are retrieved from 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, as q, a, and g. The tag values were saved to an XML File, as q, a, and g.

The following listing includes all of function getQuestions(). Function getQuestions() obtains and saves a set of questions to node list, xQuestions, a set of answers to node list, xAnswers, and a set of paths to image files to node list, xGraphics. Last getQuestions() calls showQuestion(), covered next.

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 text value from each node list. Function showQuestion() accesses the textContent property if it's available. Otherwise showQuestion() accesses the text property. Function showQuestion() retrieves one element, by index, within each NodeList. The NodeLists include xGraphics, xQuestions and xAnswers. Each node list was retrieved from XML in the Parse the XML section above.

Function showQuestion() calls functions, viewImage() and viewText(). Each function expects one String parameter. Functions viewImage() and viewText() display an image and text, respectively.

Function showQuestion() saves the answer to the current question, retrieved from node list xAnswers, to the string variable named, sCorrect. Sections of showQuestion() display below. See Controller: Surface Game Source Code for the entire showQuestion() function.

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 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.