180 likes | 201 Views
This tutorial explains how to read and parse XML files in JavaScript, using the example of a State Capital Quiz. The code demonstrates how to design XML tags, enter data, save the file, and load the data into arrays. It also provides references to further resources.
E N D
Making and Reading from XML Files Chapter 14 of Beginning JavaScript (Paul Wilton)
Code for reading XML file for State data and initializing arrays
Declare and instantiate arrays for state names and capitals var QUIZ_SIZE=5; var MyStateName = new Array(50); var MyStateCapital = new Array(50);
//loads data from xml file into the arrays (IE only) function LoadStateArray() { var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = false; xmlDoc.load("States.xml"); Declare and instantiate and ActiveX that can parse an XML file. Setting the async property to false means that the code has to wait for a response. Since the next line of code is about loading the xml file, that is what we are waiting for. Load the XML file.
for(i=0; i< xmlDoc.getElementsByTagName("state").length; i++) { MyStateName[i] = xmlDoc.getElementsByTagName("state")[i].getElementsByTagName("stateName")[0].firstChild.nodeValue; MyStateCapital[i] = xmlDoc.getElementsByTagName("state")[i].getElementsByTagName("stateCapital")[0].firstChild.nodeValue; } //end of for loop } //end of function Loop through the “state” elements. Initialize the elements of the arrays from the data in the XML file.
References • Beginning JavaScript, Paul Wilton • http://www.webopedia.com • http://www.whatis.com