Working with XML Data in Flash

If you’d like to download the file used in this tutorial to practice these techniques, visit www.layersmagazine.com and navigate to the Magazine section. All files are for personal use only.

At some point, nearly every Flash application needs to access some form of external data, which is usually in the form of an XML file. Learning how to load and process an XML file is a vital skill to have in your Flash arsenal. In this tutorial, we’ll load in data from an XML file and display it inside of the built-in DataGrid component in Flash.

1 VIEW THE STARTER FILES

Download the exercise file for this tutorial at www.layersmagazine.com and unzip it onto your desktop or other location of your choosing. Open Flash CS4 and then open the items.xml file by choosing File>Open and then navigating to it in the Open dialog. Flash actually has a minimalistic XML editor built in that shows you the XML data nicely formatted with color-coding. Now create a new ActionScript 3.0 document by choosing File>New and choosing Flash File (ActionScript 3.0) in the New Document dialog. Choose File>Save As and save this file into the same directory as the XML file that you have open.

flash

2 INSPECT THE XML FILE
If you’re already familiar with XML, then feel free to skip ahead to Step 3. For the rest of you, let’s take a look at the structure of the items.xml file. The first line is called the XML declaration and it simply declares that this is an XML document. Every XML needs to have a root tag that contains all the other tags. In this case, it’s the tag found on line 2. Inside of that you’ll see a series of tags. These contain the actual data that we’ll display inside of Flash.

flash

3 SET UP THE FLASH DOCUMENT
Go back to the new Flash document you created in Step 1. Double-click the first layer’s name and rename it “grid,” as it will contain the DataGrid component. Click the New Layer icon at the bottom of the Timeline panel and name the new layer “actions.” This layer will hold all of our ActionScript code. Lock this layer so that you can’t accidentally add any visual assets to it. The act of keeping all of your code on a single layer is considered the best practice and will keep your Flash projects more organized and clean. Consider making a template with this layer structure.

flash

4 ADD THE DATAGRID COMPONENT
Although not used very often, Flash comes with a wide assortment of prebuilt UI components for you to use. Open the Components panel by choosing Window>Components. Inside of the User Interface folder you’ll see the DataGrid component. With the grid layer selected, click-and-drag the DataGrid component onto the Stage. In the Property Inspector, give it an Instance Name of “grid.” Position it at the top left of the stage. Now, get the Free Transform tool (Q) and Option-drag (PC: Alt-drag) the bottom-right corner to resize the grid and make it fill the Stage.

flash

5 SET DATAGRID OPTIONS
All of the components that come with Flash have various options that you can set in the Component Inspector panel. With the DataGrid selected on the Stage, choose Window>Component Inspector. As you can see, there are many options available for adjustment, such as the height of the header and rows, as well as how you want the scrollbars to behave. Change the sortableColumns property from true to false as we won’t be using that feature in this example. You can now close the Components and Component Inspector panels.

flash

6 ADD SOME COLUMNS
Click the first keyframe in the actions layer to select it and open the Actions panel (Window>Actions). The first piece of ActionScript that we’ll write adds columns to the DataGrid component on the Stage. Type the code you see in the image above into the Actions panel. This adds three columns into the DataGrid, which matches the data we have contained in the XML file. You can name these columns whatever you like. For this example, I’ve kept things simple. Test the movie by pressing Command-Return (PC: Ctrl-Enter) and you should see the columns in the DataGrid.

flash

7 FETCH THE XML FILE
To get the XML data into the DataGrid, the first thing you’ll need to do is create a new instance of the URLLoader class. This is the class that will go out and retrieve the external XML file for you. When you create this object, you need to pass in the URL to the XML file inside of an URLRequest object. In this example, the XML file is in the same folder, so it’s simply “items.xml.” Type the highlighted code from the image above into the Actions panel.

flash

8 SET UP THE COMPLETE LISTENER
In the last step, we sent the URLLoader out to fetch our XML file. Now we need to let it know how to reach us when it finishes its work. We do this by registering for the complete event and have it call a function named onComplete. Type the highlighted code you see in the image above into the Actions panel. On line 6 we register for the event and then on line 8 we create the onComplete function that will be called when the data is returned.

flash

9 PASS DATA INTO XML OBJECT
When the URLLoader comes back with the data and notifies us by calling the onComplete function, we can then begin working with it. The first thing we need to do is take the raw data that was returned and put it inside of an XML object. Type the highlighted code into the Actions panel. On line 10 we take the data from the URLLoader object and pass it into a new XML object. From this point forward, Flash sees this data as XML rather than simple text.

flash

10 GETTING TO THE ITEMS
Now that we have our data as XML, we need to get to the information contained inside of the series of item tags. To do this we need a little bit of E4X, which is a new way of dealing with XML data that was introduced in ActionScript 3.0. If you do a lot of XML work, definitely get a good reference on E4X, as it’s very powerful. Type the highlighted code above into the Actions panel. On line 11 we create a new instance of the XMLList class and assign to it all of the item elements from the XML.

lashe]

11 LOOP THROUGH THE ITEMS
Now that we have all of the items stored in the XMLList object, we can loop through them and add them to the DataGrid. Before we do that we need to store the number of items in a variable so we don’t have to continually calculate that number as we go through the loop. This isn’t required but it’s a highly recommended best practice. Type the highlighted code above into the Actions panel. Line 12 stores the number of items in a variable called len and line 13 creates a simple for loop structure.

flash

12 ADD ITEMS INTO THE DATAGRID
The last thing we need to do is add the item data into the DataGrid so that users can see it. We do this by calling on the DataGrid.addItem method and passing in the data for that row. We pass in the data as an object where we tell it which piece of data goes into each column. We retrieve the actual data by accessing the current row number that is held in the i variable. For instance, to get the name of the product in the first row we could use itemList[0].name. Enter the highlighted code you see above.

flash

13 VIEW THE FINISHED GRID
Test the movie and you should see the XML data displayed nicely in the DataGrid. There are many advanced options available like having the ability to sort columns, as well as completely restyling the data to make it look however you want. Look in the Flash help files to see the full capabilities of this and other components. As a side note, if you plan on using a lot of components in your application, you may want to look into using the Flex framework, which has a much richer set of components.

flash

14 THE BENEFITS OF XML
At this point some of you may be wondering why any of this was necessary. I mean, we could’ve just put in the item data directly into the DataGrid inside of our ActionScript code. While that is true, the real power of XML is that you can change the data in your application at any time simply by modifying the XML file. Imagine if you had to open Flash and modify ActionScript code every time your data changed. This is what makes XML such a powerful tool in your Flash toolkit.

flash

Share & Enjoy


Similar Articles:

 

  1. Justam (Reply) on Monday May 24, 2010

    Thank you this information was very helpfull.

  2. luma (Reply) on Monday May 24, 2010

    Hi! Great, straight and very simple explanations. I loved it!
    How could I make a link with an item/column, suposing it has a column called “author’s website”, for instance?
    I’d really appreciate your help. Thanks!

  3. Dr. Krish (Reply) on Monday May 24, 2010

    Hi there.
    This is a great tutorial. Thank you so much. I wonder how to add some interactivity to the grid. Say for instance, when I click an item in the grid, I want to display the selected item details into a textarea with some additional xml data elments. Appreciate your time and help.
    Thank you
    Krish

  4. silverado (Reply) on Monday May 24, 2010

    When I compile the movie I get a 1120 AS3 error that says:

    “Access of undefined property itemList” on lines 12 and 15.

    Why?

  5. silverado (Reply) on Monday May 24, 2010

    Fixed. It was because in one line itemList was written with the L in lowercase.

    Sorry

  6. Tol (Reply) on Monday May 24, 2010

    How can a search field be added here when there are hundreds of items? Thank you very much in advance for assistance

  7. Girish (Reply) on Monday May 24, 2010

    I have added as3 scripting, as follows:

    ===========

    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.events.Event;

    grid.addColumn(“Name”);
    grid.addColumn(“Price”);
    grid.addColumn(“InStock”);

    var loader:URLLoader = new URLLoader(new URLRequest(“items.xml”));
    loader.addEventListener(Event.COMPLETE, onLoaded);

    function onLoaded(e:Event):void
    {
    var xml:XML = new XML(loader.data);
    var itemList:XMLList = xml..item;
    var len:int = itemList.length();
    for(var i:int=0; i<len; i++)
    {

    }grid.addItem({Name:itemList[i].name,
    Price:itemList[i].price,
    InStock:itemList[i].numInStock});
    }

    ===========

    it is shows an error, as follows

    ===========

    TypeError: Error #1010: A term is undefined and has no properties.
    at XMLDriven_fla::MainTimeline/onLoaded()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

    ===========

    Please help me…

  8. [...] Tutorial Link VN:F [1.9.7_1111]please wait…Rating: 0.0/10 (0 votes cast)VN:F [1.9.7_1111]Rating: 0 (from 0 votes) Flash, XML & Scripting [...]

  9. ... (Reply) on Monday May 24, 2010

    It does not work! DIU!

  10. amutnick (Reply) on Monday May 24, 2010

    I love this code, I am still having a hard time making items from the list clickible. How do I achieve this?

  11. R Star (Reply) on Monday May 24, 2010

    Thank you Very Much!



Planet Photoshop Photoshop World KelbyOne Lightroom Killer Tips Scott Kelby