Loading an XML document into flash

The process of loading an XML document into Flash involves the following steps:

  1. Create an XML object.

  2. Specify what happens after the XML document loads, that is, identify a function to deal with the loaded XML information.

  3. Load the external document into the XML object. Flash parses the data into the XML document tree.

After the document has been loaded and parsed into an XML document tree, an event handler calls the function specified in step 2. Usually, this function checks first to see if the XML document has been loaded successfully. If so, the function extracts the information from the XML document and adds it to the Flash movie. Its common to use the XML document to populate UI components .

Using the load method

The following code demonstrates one way to load in an external XML document. It uses ActionScript version 2.0.

 var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = functionName; myXML.load("filename.xml"); 

On the first line, I create a new XML object called myXML . The second line sets the ignoreWhite property to true. This means that Flash will ignore white space such as tabs and returns in the XML document. If you forget to set this property, blank lines will be treated as nodes, which can cause problems when youre trying to extract information.

On the third line, I use the onLoad event handler to refer to the function that will be called after the file has loaded. In the example, Ive used the name functionName . The last line loads the file called filename.xml . If this were a real example, Id have to create the function called functionName to process the XML content from filename.xml after the file loads.

I can also load the XML document from a subdirectory of the current directory:

 var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = functionName;  myXML.load("foldername/filename.xml");  

Be aware that if your XML document includes file names and file paths, storing the XML document in a subfolder might cause you problems. When you try to use this information in a movie, Flash calculates the relative paths from the location of the . swf file. As this may be in a different location from the XML or .swf file, the movie may not be able to find the files at those locations. To avoid these potential problems, its much easier if you keep your XML document in the same folder as your Flash movie.

In the code youve seen so far, Ive used a file name ending with the .xml extension. However, you arent limited to this type of file. You can load any type of file providing it results in an XML document. This means that you can load a server-side PHP, ColdFusion, Java, or ASP.NET file as long as it generates XML content.

If you do load a server-side file into your XML object, youll need to include the full path so that the web server can process the server-side code. Ive shown an example here; well learn more about working with server-side documents a little later in this chapter.

 var myXML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = functionName;  myXML.load("http://localhost/webfolder/filename.aspx");  

Understanding the order of the code

You may have noticed that, in the code samples above, I specified the load function before I loaded the XML document. On the surface, this doesnt make sense. Shouldnt I wait until the XML file loads and then specify which function to call?

In Flash, some ActionScript code doesnt run in a strict order. Lines dont necessarily wait for other lines to complete before they run. Much of the code that we write is in response to a specific event such as a mouse click. In this case, the event is the loading of an external XML file into an XML object. We call this asynchronous execution.

If we specified the load function after the load line, the XML file might have already finished loading before we set the function that should be called. This would mean that the onLoad function would be skipped completely. The only way to be sure that you call the function correctly is to set a reference to it before you load the XML file.

Understanding the onLoad function

After the XML document has finished loading, Flash calls the function that you specified in the onLoad line. The function is called by the onLoad event handler , and it runs after the XML document has been received by Flash and parsed into the document tree. You can assign the onLoad function with the following line:

 myXML.onLoad = functionName; 

If youve worked with ActionScript before, youll notice that the function doesnt include those brackets that youre used to seeing after the function name, for example, functionName() . Thats because were not actually calling the function in this line; instead, were assigning it to the onLoad event handler. The call will happen after the XML document is loaded and parsed.

Any onLoad function that you create automatically includes a parameter that tells you whether or not the file loaded successfully. The onLoad function should always test this parameter first before you start to process the XML document. You can also check the status property of the loaded document to see if there were any problems.

You can see this process in the following sample code:

 var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = myFunction; myXML.load("filename.xml");  function myFunction(success:Boolean):Void {   if (success) {   //process XML content   }   else {   //display error message   }   }  

In these lines, Ive defined the function myFunction with a parameter called success . You can use any name you like for this parameter. The important thing to remember is that the parameter is Boolean, so it can only have one of two values: true or false .

The first line in the function checks to see if the value of the parameter is true ; that is, if the XML document has loaded successfully. If so, the function would normally then include lines that process the XML content. Otherwise, if the document didnt load successfully, wed probably want to display an error message.

Using the line

 if (success) { 

is equivalent to using

 if (success == true) { 

I could also have used an inline function as shown here:

 var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = function (success:Boolean):Void {   if (success) {     //process XML content   }   else {     //display error message   } }; myXML.load("filename.xml"); 

Either of the two approaches shown here is acceptable. If you create the onLoad function separately, rather than inline, you will be able to reuse it when you load other XML documents. After all, if your XML documents have the same structure, youll probably want to process them in the same way. Using the same function allows you to reuse the code and means that youll only have to maintain one block of ActionScript. If youre loading a single XML document into your movie, it doesnt matter which method you choose.

The code shown so far uses the onLoad event handler. Flash provides another event handler for the XML object: onData . Both events trigger after the content has been loaded into Flash. The difference is that the onLoad event happens after the XML content has been parsed by Flash and added to the XML document tree. The onData event takes place before parsing, so you can use this event to access the raw XML from your external document. In most cases, youll use the onLoad event handler.

image from book

In case youre wondering what the :Void means in myFunction(success:Boolean):Void , it indicates what type of information the function returns. In this case, nothing is returned, so Ive used the word Void . You could also specify the datatype for the value returned by the function, for example, String or Number .

image from book
 

After you load the XML content into an XML object, youll need to add the data to your Flash movie. Before you do this, you should check that the document has loaded successfully.

Testing if a document has been loaded

You can test whether an XML document has been loaded by checking the loaded property of the XML object. The property returns a Boolean value and will display either true or false when traced in an Output window. Heres an example:

 var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = function (success:Boolean):Void {  trace (this.loaded);  }; myXML.load("filename.xml"); 

In the sample code, this refers to the XML object. I can use the keyword this because Im inside the onLoad function for the XML object.

Note that the loaded property may return a value of true even when errors have occurred in parsing the XML content. Flash provides a mechanism for finding errors.

Locating errors in an XML file

When you load an external XML document into Flash, its possible that it may not be well formed. Remember that well- formed documents meet the following requirements:

  • The document contains one or more elements.

  • The document contains a single root element, which may contain other nested elements.

  • Each element closes properly.

  • Start and end tags have matching case.

  • Elements nest correctly.

  • Attribute values are contained in quotes.

Where a document is not well formed, Flash may have difficulty in parsing it into the document tree. Flash may still indicate that the document has loaded successfully, even if it wasnt parsed correctly.

The XML class has a status property that indicates any problems that occurred when parsing the XML document. This property returns a value between and ˆ 10 ; the values for each are shown here:

  • No error; the parse was completed successfully.

  • ˆ 2 A CDATA section was not properly terminated .

  • ˆ 3 The XML declaration was not properly terminated.

  • ˆ 4 The DOCTYPE declaration was not properly terminated.

  • ˆ 5 A comment was not properly terminated.

  • ˆ 6 An XML element was malformed .

  • ˆ 7 The application is out of memory.

  • ˆ 8 An attribute value was not properly terminated.

  • ˆ 9 A start tag was not matched with an end tag.

  • ˆ 10 An end tag was encountered without a matching start tag.

Where a document contains multiple errors, the status property will only return one error value. Even though Flash may detect an error during parsing, it may still be possible to find information from all or part of the document tree.

To show you an example of the status numbers , lets load the resource file address1.xml file into Flash. The document is missing an ending </phoneBook> tag, as shown here:

 <?xml version="1.0" encoding="UTF-8"?> <phoneBook>   <contact id="1">     <name>Sas Jacobs</name>     <address>123 Some Street, Some City, Some Country</address>     <phone>123 456</phone>   </contact> 

Ive saved this example in the resource file simpleloadstatus.fla . Figure 4-1 shows the status code that displays when I test the file. In this case, the code is ˆ 9 , indicating a mismatch between start and end tags within the document.

image from book
Figure 4-1: The Output window displaying the status property

So far, weve covered the theory behind loading external XML documents into Flash. We create an XML object and load a file, and Flash parses the contents into a document tree. We can then use a function to add the XML content to our movie.

Each time you load an external XML document, your code will probably start with the same steps:

  1. Create the XML object.

  2. Set the ignoreWhite property to true.

  3. Specify the name of the function that will deal with the loaded XML document.

  4. Load the XML document.

  5. Within the load function, test whether the XML file has loaded successfully.

  6. Display the document tree with a trace action to check the loaded contents.

Well work through an example to illustrate these steps. Well load an external XML document into Flash and display it in an Output window. When you do this, you should see the same content that is in the external document.

Exercise 1: Loading an external XML document
image from book

In this example, well create a simple Flash movie that loads the address.xml file and displays it in an Output window. You can see the completed example in the resource file simpleload.fla .

  1. Create a new Flash movie and click frame 1 on the Timeline.

  2. Save the document in the same folder as the address.xml file.

  3. Add the following code into the Actions panel. You can open the panel by using the F9 shortcut key.

     var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = processXML; myXML.load("address.xml"); function processXML(success:Boolean):Void {   if (success) {     trace(this);   }   else {     trace ("Error loading XML file");   } } 

In this example, I call the function processXML after the file address.xml loads. The function checks to see if the XML document loads successfully by checking the variable success . If so, I use the trace action to display the XML document tree in an Output window. If not, I display an error message in the Output window.

Because the function has been called by the onLoad event of the XML object, I can use the word this . In fact,

 trace(this); 

is the same as

 trace(myXML); 
  1. Save the movie and test it with the CTRL-ENTER shortcut ( CMD-RETURN on a Macintosh). You should see an Output window similar to the one shown in Figure 4-2. The Output window displays the document tree from the XML object. Ive saved the sample file simpleload.fla with your resources.

    image from book
    Figure 4-2: The Output window displaying XML content

  2. If you see an error when you test the movie, its most likely to be due to a misspelling. Check the XML document file name and the spelling of your success parameter within the function. A sample error is shown in Figure 4-3.

    image from book
    Figure 4-3: The Output window displaying an error message

In the previous exercise, we loaded the file address.xml into Flash. We tested that the document loaded successfully, and then we displayed the contents of the XML document tree in an Output window. Tracing the document tree can be a useful way to test that youve loaded the XML document correctly.

With most objects in Flash, youll see [object Object] when you trace them in the Output panel. If you trace an XML or XMLNode object, Flash uses the toString method to display a text representation of the object. This is very useful when you want to view the XML document tree. Using

 trace(myXML); 

is the same as using

 trace(myXML.toString()); 

Points to note from exercise 1

  • Its possible for you to change the XML content within Flash independently of the external XML document. Flash doesnt maintain a link back to the original document. If the external document changes, it will have to be loaded again before the updated content displays within Flash.

  • Flash cant update external documents. To update an external XML document, youll have to send any changes you make to the document tree out of Flash to a server-side page for processing.

  • Earlier in the chapter, I discussed inline onLoad functions. Ive re-created the preceding example using an inline function. The code is shown here, and its saved in the resource file simple load2.fla :

     var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = function(success:Boolean):Void {   if (success) {     trace(this);   }   else {     trace ("Error loading XML file");   } }; myXML.load("address.xml"); 
image from book
 

Testing for percent loaded

Loading a large XML document might take some time, and its useful to let the user know whats happening. You may want to display a message showing the user that the XML file is loading. The XML class allows you to find out how big the XML file is and how much has loaded, using the getBytesLoaded and getBytesTotal methods .

You can use these methods with the setInterval action to check progress at given time intervals. You can also use them in the onEnterFrame event handler of a movie. Loading small XML files is very quick, so these methods are only going to be useful when youre working with large XML files.

The following example is based on the code provided within the Flash help file. It shows how you can test for the percentage of an XML file loaded using the setInterval action. You can find the example in the resource file simpleloadpercent.fla .

 var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = processXML; var intervalID:Number = setInterval(checkLoad, 5, myXML); myXML.load("large.xml"); function processXML(success:Boolean):Void {   clearInterval(intervalID);   if (success) {     trace("loaded: " + this.getBytesLoaded());     trace ("total: " + this.getBytesTotal());   }   else {     trace ("Error loading XML file");   } } function checkLoad(theXML:XML):Void {   var loaded:Number = theXML.getBytesLoaded();   var total:Number = theXML.getBytesTotal();   var percent:Number = Math.floor((loaded/total) * 100);   trace ("percent loaded: " + percent); } 

On my computer, despite loading an XML file of over 3 MB in size, the loading process only displays the total file size .

The following example shows the same methods used with the onEnterFrame event handler. You can see the example saved in the resource file simpleloadEnterFrame.fla .

 var myXML:XML = new XML(); myXML.ignoreWhite = true; myXML.onLoad = processXML; var intervalID:Number = setInterval(checkLoad, 5, myXML); myXML.load("large.xml"); this.onEnterFrame = function():Void {   var loaded:Number = myXML.getBytesLoaded();   var total:Number = myXML.getBytesTotal();   var percent:Number = Math.floor((loaded/total) * 100);   trace ("percent loaded: " + percent);   if (percent == 100) {     delete this.onEnterFrame;   } } function processXML(success:Boolean):Void {   if (success) {     trace("loaded: " + this.getBytesLoaded());     trace ("total: " + this.getBytesTotal());   }   else {     trace ("Error loading XML file");   } } 

Again, I am not able to get the percentage loaded value to display each time the movie enters a new frame. You may wish to use these methods with caution. In my work, using a preloader for XML documents has rarely been necessary. If required, an alternative approach might be to show and hide a movie clip that displays a loading message.

After youve loaded an external XML document, youll need to display the contents within your Flash movie. The next section shows how you can extract information from an XML object. A little later, well use the techniques to populate UI components.



Foundation XML for Flash
Foundation XML for Flash
ISBN: 1590595432
EAN: 2147483647
Year: 2003
Pages: 93
Authors: Sas Jacobs

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net