180 likes | 290 Views
Making and Reading from XML Files. Chapter 14 of Beginning JavaScript (Paul Wilton). File/New/File. Choose an XML File template and click Open. Start of XML File. Design tags and enter data. In the Data view. Save file. Saving File. Enter more data and save. State Capital Quiz design.
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