May 3, 2009

How to parse a XML file using ActionScript 3.0

Here is an example on how to get data from XML file using ActionScript 3.0.

XML file example:

<?xml version="1.0" encoding="utf-8"?> <Data>     <Title font="Arial">         XML Example     </Title>     <HTML_Example>         <![CDATA[You can add html text here.]]>     </HTML_Example>     <List>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>         <URL>http://www.mariuscristiandonea.com</URL>     </List> </Data>

ActionScript 3.0 code:

var XMLLoader:URLLoader; var XMLPath:URLRequest; var XMLDoc:XMLDocument = new XMLDocument(); XMLDoc.ignoreWhite = true; XMLPath = new URLRequest("test.xml"); XMLLoader = new URLLoader(XMLPath); // Call extractXMLFileData function if the XML file does load. XMLLoader.addEventListener("complete", extractXMLFileData); // Call errorXMLFileData function if the XML file didn't load. XMLLoader.addEventListener("ioError", errorXMLFileData); // This function parse the data from the XML file, if it is loaded. function extractXMLFileData(event:Event):void {     var XMLData:XML = XML(XMLLoader.data);     XMLDoc.parseXML(XMLData.toXMLString()); // Define the first node.     var DataNode:XMLNode = XMLDoc.firstChild; // Read a node attribute.     trace(DataNode.firstChild.attributes.font); // Read a node value.     trace(DataNode.firstChild.firstChild.nodeValue); // Here we read the node value that contains the HTML text.     trace(DataNode.childNodes[1].firstChild.nodeValue); // In the next "for" we read all the URL nodes.     for (var currentNode = DataNode.childNodes[2].firstChild; currentNode != null; currentNode=currentNode.nextSibling)     { // If the name of the node is "URL" then we read the value from it.         if (currentNode.nodeName == "URL")         {             trace(currentNode.firstChild.nodeValue);         }     } } // This function takes action if the XML file didn't load. function errorXMLFileData(event:Event):void {     trace("Error! The XML file didn't load!"); }

Leave a Comment