Friday, December 19, 2008

Flash as3 load xml data

This is how we load xml to flash using actionScript 3.0



//Create the loader, set dataFormat to text
//and listen when data is loaded
var loader:URLLoader = new URLLoader()
loader.dataFormat = URLLoaderDataFormat.TEXT
loader.addEventListener(Event.COMPLETE, onLoadXML)
loader.load(new URLRequest("anastasio.xml"))
function onLoadXML(ev:Event){
   
try{       
//Convert the downloaded text into an XML        
var myXML:XML = new XML(ev.target.data)      
var list:XMLList = myXML.data.title     
//walks the list and show in textfields    
for(var i=0; i<list.length(); i++){         
//trace(list[i].@name+"-"+list[i].comments+" - "+list[i].image)           
this["Title_txt"+i].text = list[i].@name          
this["Comments_txt"+i].text = list[i].comments         
var loader:Loader = new Loader()         
this["holder_mc"+i].addChild(loader)           
loader.load(new URLRequest(list[i].image))                

} catch (e:TypeError){       
//Could not convert the data, probavlu because       
//because is not formated correctly       
trace("Could not parse the XML")        
trace(e.message)    
}
}


:::::::another way:::::::

var xmlloader = new URLLoader();
xmlloader.addEventListener(Event.COMPLETE, handleComplete);
xmlloader.load(new URLRequest("test.xml"));

function handleComplete(e:Event):void {
var xDoc:XMLDocument = new XMLDocument();
xDoc.ignoreWhite = true;
var theXML:XML = XML(e.target.data);
xDoc.parseXML(theXML.toXMLString());
var value1 = new Array();
var value2 = new Array();
var value3 = new Array();
var value4 = new Array();
var value5 = new Array();

for (var v:Number = 0; v < xDoc.firstChild.childNodes.length; v++) {
value1.push(xDoc.firstChild.childNodes[v].childNodes[0].firstChild.nodeValue); value2.push(xDoc.firstChild.childNodes[v].childNodes[1].firstChild.nodeValue); value3.push(xDoc.firstChild.childNodes[v].childNodes[2].firstChild.nodeValue); value4.push(xDoc.firstChild.childNodes[v].childNodes[3].firstChild.nodeValue); value5.push(xDoc.firstChild.childNodes[v].childNodes[4].firstChild.nodeValue);
}

}

No comments: