XML Parsing
Part 1
Open notepad and create a paste the following XML code into the file.
<?xml version="1.0" encoding="utf-8"?> <Books> <Book ISBN="00000001"> <Title> Flash CS4 Magic</Title> <author> Flash Gordon</author> </Book> <Book ISBN="0000002"> <Title> ActionScript CS4 Magic</Title> <author>Paul Daniels</author> </Book> </Books>
The save the file as data.xml.
Next open a new flash document. Then open the components panel and select the textArea component and drag this to the stage. Resize the component so that it is 300 x 200.
From the previous weeks tutorial you should be able to load a XML file into flash, create the code to do this. The Event.COMPLETE should call the xmlLoaded function.
Now add the following code:
function xmlLoaded(event:Event):void{
books = new XML(loader.data);
parseXML(books);
}
// displays all the data from XML file in text box
function parseXML(booksData:XML):void{
// displays the authors
my_text.text = booksData.Book.author.toXMLString();
// displays the number of books in the file
my_text.text += "Number of books =" + booksData.Book.length();
}
The xmlLoaded functions simply assigns the data to a xml variable called books. This variable is then passed into the parseXML function. The Books.Data.Book.author is a reference to the element we are interested in from the XML data structure. The toXMLString simply returns the value of the XML object as a string.
The .length function simply returns how many elements of the Book are within the XML data structure in this case it will return 2.
Part 2
Suppose you were only interested in getting the data relating to the authors. To do this amend the function above so that it is:
var authorList:XMLList;
// displays all the authors
function parseXML(booksData:XML):void{
authorList = booksData.Book.author
for (var i:int = 0; i < authorList.length(); i++){
var authorElement:XML = authorList[i];
my_text.text +=authorElement;
}
}
Here we are creating a new XML list called authorList and attaching the data to this list. Then a for loop is created to loop through the new list and assign the data to an xml variable. Which is then displayed in the text area
Excercise
Now either create a new function that will display the title of the book only in the textarea or modify the existing function. The author list should be underneath the list of books e.g. book 1, book2 then author1, author2.
