Accessibility

ActionScript cookbook beta

Load and read XML

Problem Summary

You need to load and read an XML file.

Solution Summary

Use the URLLoader API to load the XML and the E4X XML API to parse it.

Explanation

ActionScript 2

function onXMLLoad(success:Boolean):Void
{
   trace(this);
   trace("Number of Contacts : " + this.firstChild.childNodes[0].childNodes.length);

   var firstPerson:XMLNode = this.firstChild.childNodes[0].childNodes[0];
   var nodes:Array = firstPerson.childNodes;
   var nodeLen:Number = nodes.length;
   
   var node:XMLNode;
   var favoriteFood:String;
   for(var i:Number = 0; i < nodeLen; i++)
   {
      node = nodes[i];
      if(node.nodeName == "favoriteFood")
      {
         favoriteFood = node.firstChild.nodeValue;
      }
   }
   trace("First contact’s favorite food : " + favoriteFood);
}

var my_xml:XML = new XML();
my_xml.onLoad = onXMLLoad;
my_xml.ignoreWhite = true;
my_xml.load("contacts.xml");

ActionScript 3

function onXMLLoad(event:Event):void
{
   var xml:XML = new XML(event.target.data);
   trace(xml);
   trace("Number of Contacts : " + xml..person.length());
   trace("First contact’s favorite food : " + xml.contacts.person[0].favoriteFood);
}

var loader:URLLoader = new URLLoader();
var url:URLRequest = new URLRequest("contacts.xml");
loader.addEventListener(Event.COMPLETE, onXMLLoad);
loader.load(url);

Note: Both examples use the following XML contained in a file called contacts.xml:

<xml>
   <contacts>
      <person>
         <name>Mike Chambers</name>
         <favoriteFood>Bacon</favoriteFood>
      </person>
      <person>
         <name>John Doe</name>
         <favoriteFood>Pez</favoriteFood>
      </person>
   </contacts>
</xml>

In the ActionScript 3 example this in the onXMLLoad function refers to the timeline that contains the code, while in the ActionScript 2 example, this refers to the XML object instance.