Search Flex Components Free

Custom Search

December 27, 2007

AS3 Using XML data and parse it to a List Component - FLASH CS3

Using AS3 to load XML data it's quite different than using AS2. In this tutorial I will explain to you, how we can load an external XML data, bring it to the fla file, and parse it to a List component. Using your notepad or similar program, make a simple XML file like the above example.

<?xml version=”1.0″ encoding=”iso-8859-1″?>

<news>
<item date = “ 01/01/2007 “ >
<title> news1 </title>
<description> Lorem ipsum elitrgh dolor sit amet, consectetuer adipiscing elit. Maecenas vitae nisi. </description>
<pic> japao1 </pic>
</item>
<item date = “ 02/02/2007 “ >
<title> news2 </title>
<description> Lorem ipsum elitrgh dolor sit amet, consectetuer adipiscing elit. Maecenas vitae nisi. </description>
<pic> japao2 </pic>
</item>
<item date = “ 03/03/2007 “ >
<title> news3 </title>
<description> Lorem ipsum elitrgh dolor sit amet, consectetuer adipiscing elit. Maecenas vitae nisi. </description>
<pic> japao3 </pic>
</item>
<item date = “ 04/04/2007 “ >
<title> news4 </title>
<description> Lorem ipsum elitrgh dolor sit amet, consectetuer adipiscing elit. Maecenas vitae nisi. </description>
<pic> japao4 </pic>
</item> </news>

Save it at the same directory as your fla file, naming it as news.xml . Now, the first step to load the xml file, we use the following code:


var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);

xmlLoader.load(new URLRequest(”news.xml”));

As you are using AS3, every time we define a variable, we must identify, which kind of variable is it. In the above code we say that the variable xmlLoader belongs to the URLLoader class ( xmlLoader:URLLoader ) , and the xmlData is the type XML ( xmlData:XML ). When the data is loaded, we must say to the code “where to go”. It's an event, so xmlLoader.addEventListener(Event.COMPLETE, LoadXML); , it's the same as saying that when the xml data was completely loaded, then calls the function LoadXML. Now drag a List component into stage, and name it as my_lst .

The following code will define which data we want to show on the List component, as also parse into it.

function LoadXML(e:Event):void {

xmlData = new XML(e.target.data);

ParseNews(xmlData);

}

function ParseNews(newsXML:XML):void {

var newsList:XMLList = newsXML.item.title;

f or each (var newsTitle:XML in newsList) {

my_lst.addItem({label:newsTitle, data:newsTitle});

}

}

Run your movie.

Related Flex Tutorials