Wednesday, April 20, 2011

AS3 Code: XML

//create .xml file



//save .swf file in the same folder as .xml file
//request the file
var myRequest:URLRequest = new URLRequest("xmlfile.xml");

//create a loader
var myLoader:URLLoader = new URLLoader();

//create an event listener for when file is loaded
myLoader.addEventListener(Event.COMPLETE,onXMLload,false,0,true);

//load the file
myLoader.load(myRequest);

//tell Flash it is XML data
var myXML:XML;

function onXMLload(e:Event):void{
    myXML = new XML(e.target.data);
    trace(myXML); //to see if it loaded successfully
    //shows all xml file data

    trace(myXML.length()); //similar to accessing array info
    //1
    trace(myXML.image.length()); //# of image tags in file
    //3
    trace(myXML.image[0]);
    //shows first image tags & what's included between tags
    trace(myXML.image[0].pic);
    //images/myImg1.jpg
    trace(myXML.image[0].@title); //to access attribute, use @
    //My First Image
}

//if XML load has an error
myLoader.addEventListener(IOErrorEvent.IO_ERROR,onError,false,0,true);

//if everything works, this won't be called
function onError(e:IOErrorEvent):void{
    trace("xml didn't load");
    trace(e);
}


0 comments:

Post a Comment