Recipe 19.11 Loading XML

19.11.1 Problem

You want to load XML data from an XML document or a server-side script that generates XML.

19.11.2 Solution

Use the XML.load( ) method to load the data. Define an onLoad( ) method to handle the results.

19.11.3 Discussion

The load( ) method loads XML data from the URL that you specify:

my_xml = new XML(  );

// Initiate the loading of an XML document in the same directory as the .swf file.

To meaningfully process the XML data that loads, you must define an onLoad( ) method for the XML object on which you called load( ). The onLoad( ) method is automatically invoked when the data loads, and it is passed a Boolean value indicating whether the XML data was successfully parsed. It is up to you to define the onLoad( ) method so that it processes the XML data in the way that you want it to.

my_xml.onLoad = function (success) {
  if (success) {
    trace("The XML was successfully parsed. Here are the contents: ");
  } else {
    trace("There was an error parsing the XML data");

You should, almost without exception, set the XML object's ignoreWhite property to true before you load any XML data into a Flash movie. Otherwise, the ActionScript XML parser creates whitespace nodes for any space, tab, carriage return, newline, or form feed character. The resulting data is much more difficult to handle because you have to contend with excess whitespace nodes. Setting the ignoreWhite property to true causes the parser to automatically ignore whitespace and not create separate whitespace elements in the data. You must set the property to true prior to the parsing of the data. In practical terms this means you should set the property to true before you call the load( ) method. See a more detailed discussion in Recipe 19.12.

my_xml.ignoreWhite = true;

Setting ignoreWhite on the prototype sets it for all XML objects:

XML.prototype.ignoreWhite = true;

19.11.4 See Also

Recipe 19.12

    Part I: Local Recipes
    Part II: Remote Recipes