May 3, 2009

How to parse a XML file using ActionScript 3.0

Here is an example on how to get data from XML files 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);
XMLLoader.addEventListener("complete", extractXMLFileData); // Call extractXMLFileData function if the XML file does load.
XMLLoader.addEventListener("ioError", errorXMLFileData); // Call errorXMLFileData function if the XML file didn’t load.

function extractXMLFileData(event:Event):void // This function parse the data from the XML file, if it is loaded.
{
    var XMLData:XML = XML(XMLLoader.data);
    XMLDoc.parseXML(XMLData.toXMLString());
    var DataNode:XMLNode = XMLDoc.firstChild; // Define the first node.

    trace(DataNode.firstChild.attributes.font); // Read a node attribute.
    trace(DataNode.firstChild.firstChild.nodeValue); // Read a node value.
    trace(DataNode.childNodes[1].firstChild.nodeValue); // Here we read the node value that contains the HTML text.

    // In the next "for" we read all the URL nodes.
    for (var currentNode = DataNode.childNodes[2].firstChild; currentNode != null; currentNode=currentNode.nextSibling)
    {
        if (currentNode.nodeName == "URL") // If the name of the node is "URL" then we read the value from it.
            {trace(currentNode.firstChild.nodeValue);}
    }
}

function errorXMLFileData(event:Event):void // This function takes action if the XML file didn’t load.
{
    trace("Error! The XML file didn’t load!");
}

Leave a Comment