19.16. Using XML Data to Initialize a Movie

Problem

You want to use XML data from an external source to initialize certain elements of your Flash movie.

Solution

Use the XML.load( ) method to load the XML data, and then initialize the movie’s elements within the onLoad( ) method.

Discussion

One of the many uses for XML within your Flash movie is initializing elements such as menus, navigation elements, news, headlines, and so on. By loading the data from an external source, you can more easily update the values or even generate them from a database. This is extremely important for applications in which the content changes frequently, such as product catalogs, news sites, and message boards. To initialize your movie using XML data, load the data using the XML.load( ) method, and then perform the initialization within the onLoad( ) method (or within a function called by onLoad( )):

my_xml = new XML(  );
my_xml.load("myAppValues.xml");
my_xml.onLoad = function (  ) {
  
  /* This example populates a list box with message titles and  
     IDs from XML data that might look something like this:
      <messages>
       <message>
         <title>XML fun</title>
         <id>0</id>
       </message>
       <message>
         <title>more XML fun</title>
         <id>1</id>
       </message>
       <message>
         <title>XML fun yet</title>
         <id>2</id>
       </message>
     </messages>
  */
  var messages = this.firstChild.childNodes;
  for (var i = 0; i < messages.length; i++) {
    _root.messagesLB.addItem(messages[i].firstChild.firstChild.nodeValue, 
                             messages[i].lastChild.firstChild.nodeValue);
  }
};

See Also ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.