Parse XML with JavaScript

Free HTML5 Game Tutorial for Beginners: Page 19

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.

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.

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.
LastgetQuestions() calls
showQuestion(), covered next.

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

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

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.

Game Tutorial for Beginners was prepared for the Web in 2012.
HTML5, CSS3, and JavaScript have improved over time.
Game Tutorial for Beginners doesn't include state of the art
technology, yet still contains many useful features and ideas.