AS2 to AS3 Baby Steps - Part 5 - Parsing XML

Reynaldo November 13th, 2007

Now that Flash AS3 uses E4X as its core XML engine, things have REALLY changed from that old childNode stuff we were used to in AS2. For starters, parsing XML is now much more clear and straight forward.

It was a huge pain parsing xml in AS2. You would have to follow along the actual xml file to know what each node or childNode represented. But not any more! ( kinda ;) )

Sample xml file:

1
2
3
4
5
6
7
8
< profiles >
    < employee file="files/emp1.png" id="1" >
        < name >Reynaldo Columna< /name >
    < /employee >
    < employee file="files/emp2.png" id="2" >
        < name >Nicole Columna< /name >
    < /employee >
< /profiles >

This is how we used to parse the file in AS2:

1
2
3
4
5
6
7
8
9
10
11
var xmlData:XML = new XML();xmlData.ignoreWhite = true;
 
xmlData.onLoad = parseXMLData;
 
xmlData.load("employees.xml");function parseXMLData():Void
{
  var strEmployee1:String = xmlData.firstChild.childNodes[0].attributes.file;
  var strName1:String = xmlData.firstChild.childNodes[0].childNodes[0].firstChild;
  trace("Path to picture of first employee: " + strEmployee1);
  trace("Name of the first employee: " + strName1);
}

And now this is the new way of parsing in AS3

1
2
3
4
5
6
7
8
9
10
11
12
var strXML:String = "employees.xml";
var xmlLoader:URLLoader = new URLLoader();xmlLoader.addEventListener(Event.COMPLETE, parseXMLData);
xmlLoader.load(new URLRequest(strXML));
 
function parseXMLData ($event:Event):void
{
  var xmlData:XML = new XML(xmlLoader.profiles);
  var strEmployee1:String = xmlData.employee[0].@file;
  var strName1:String = xmlData.employee[0].name;
  trace("Path to picture of first employee: " + strEmployee1);
  trace("Name of the first employee: " + strName1);
}

Lets go through the code briefly. First off you can notice that we used the URLLoader class discussed earlier in this series to load the xml file. We then subscribe to the COMPLETE event fired once the xml file is loaded and run the parseXMLData function, so far so good. Now we load the file witht eh help of the URLRequest class also discussed earlier.

Now comes the parsing part. We need to take the loaded information and tell flash that this data is xml data, hence we plug it into a “new XML()” now we can run through the data as if it was on object holding and array of objects much like XPath.

There’s much more to it that I will discuss in a later more advanced post never the less, play around with it!

Happy coding!

Trackback URI | Comments RSS

Leave a Reply

  • Friends

  • Props

  • Donations

  • website counter
  • Archives

  • Feedburner