Home > Articles

Getting Your Feet Wet

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

This chapter provides your first steps into Flash-XML integration. There's no better way to learn than by doing, so we're going to get into an example right away. The example will cover loading a simple XML document in Flash and teach the basics of Flash's handling of XML, with its built-in XML object. At the end of this chapter, you will essentially be able to load information from the Web server into your Flash movie at runtime (that is, while it is running in the user's browser). This is exactly the kind of capability you want to be able to create a Flash movie for a Web site, one that requires a content change from time to time. Just changing the contents of the loaded XML file will change how that Flash movie appears, making it easily updatable (and even automatically updatable, as you'll see in Part II, "Flash and Dynamic XML").

First, you'll be importing an XML document in Flash and accessing that data. The example will be as simple as possible, but it should give you a good idea of how this stuff works.

Next, you'll learn about the basics of Flash's XML object. Flash automatically puts imported XML into its own ActionScript object with the novel name of "XML object." You'll learn a bit about this object as you try to access the information in it. Later chapters will certainly explore the object, its methods, and its properties in greater detail, but this chapter will be essential to understanding the fundamentals.

Importing XML into Flash

Now is the time to fire up Flash, and put down your honey-glazed cruller. Create a new Flash file (an FLA), and save it as simpleXMLexample.fla in a convenient directory of your choosing. In the same directory, create a text file using your favorite plain text editor. Microsoft Word is not particularly good at plain text editing because it tends to format everything in its own rich text format. Notepad, on the other hand, is completely acceptable, as is SimpleText if you're on a Mac. Enter the following XML into the text document:

<?xml version="1.0" encoding="UTF-8"?>
<recipe>
  <name>peanut butter and jelly sandwich</name>
  <ingredient_list>
    <ingredient quantity='2 tbsp'>
      peanut butter
    </ingredient>
    <ingredient quantity='2 tbsp'>
      jelly
    </ingredient>
    <ingredient quantity='2 slices'>
      bread
    </ingredient>
  </ingredient_list>
</recipe>

Save the file as "pbj.xml" and give it a quick check in Internet Explorer to reveal whether any typos or other problems exist. When you've checked the XML document and fixed any errors, you're ready to load it into Flash.

Return to your empty simpleXMLexample.fla. Open your ActionScript editor for the first frame by double-clicking that frame in the timeline. Enter the following ActionScript:

recipeXML = new XML(); 
recipeXML.onLoad = function (success) { trace("Loaded!");}
recipeXML.load ("pbj.xml");

A quick test of this FLA in your Flash editing environment (choose Control | Test from the menu) should bring up the trace window with a message of "Loaded!". If this does not occur as described here, go back and ensure that your XML file has the correct name and is saved in the same directory as your FLA. You'll also want to make sure you've written the ActionScript exactly as it's shown in the preceding code lines. Keep in mind that the trace() function works only in the Flash editing environment, so there's no point in trying this in your browser. If everything went well and you have seen the "Loaded!" message, then you have successfully loaded your first XML document. It should look similar to Figure 3.1.

Figure 3.1 This figure shows that the XML was loaded successfully.

It doesn't look like much right now, but it's really the beginning of many things to come. Before you do something more useful, like extracting the data, take a look at what that ActionScript was actually doing.

Step 1: Create an XML Object

In the first line, the ActionScript says the following:

recipeXML = new XML();

XML() is the method that creates the XML object. You can tell what the method's purpose is because it has the same name as the XML object. For that reason, the XML() method (and methods like it for other objects) is called a constructor method. By using the new keyword, this method knows that it needs to return a reference to an object. That reference is then stored in the name you've created called recipeXML. After this, recipeXML will be an XML object.

Step 2: Override the onLoad() Handler Method

The onLoad() method in the second line of code is another special kind of method of the XML object:

recipeXML.onLoad = function (success) { trace("Loaded!");}

Now that you have an XML object called recipeXML, you need to tell it what to do after XML has been loaded into it. When Flash finishes reading XML (such as "pbj.xml") into your XML object (recipeXML), it automatically calls the onLoad() method . Methods that work this way are often referred to as event handlers because of the way they are called to handle events (the loading of XML, in this case). By default, the XML.onLoad() method does nothing, but you would like it to tell you when the XML is loaded. The only way to achieve that kind of functionality is to override the default onLoad() method of the XML object for your object, recipeXML.

The way that we've overridden that method in the preceding line of code is a little tricky and probably warrants some explanation. The following several lines of code work exactly the same as the previous one line of code, but it might make more sense spread out:

function aBetterOnLoad (success) {
 trace("Loaded!");
}
recipeXML.onLoad = aBetterOnLoad;

The code starts with a function definition that takes an argument named success, and then calls a trace() function with the string "Loaded!". That's simple enough. You don't know what success is (yet), but whatever it is, the string "Loaded!" will show up in Flash's Output window.

After defining that function, you set your object's onLoad() method to be equal to that new function. In that way, you override the default onLoad() method with your own aBetterOnLoad() function. From now on, when Flash calls onLoad() automatically, it will call your aBetterOnLoad() function. Now you have precise control over what Flash does when it loads XML into your recipeXML object.

Instead of messing around with creating and naming an otherwise unrelated function, you simply compress those lines into a more concise version:

recipeXML.onLoad = function (success) { trace("Loaded!");}

So what about success? It's an argument that indicates whether the XML was loaded successfully. It contains a true or false value, and you can do whatever you want with that information. In this example, we've done absolutely nothing with it, although we could have just as easily written something like this:

recipeXML.onLoad = function (success) { 
trace("Loaded!");
trace(success);
}

Chances are that if you try this code, you're going to see something similar to Figure 3.2.

Figure 3.2 The result when success is true.

The only time success would be false is if the file didn't exist as you've called it, or if you're requesting the file from a network resource (such as a Web server) and a network error occurs (like the Web server has crashed). Errors in your actual XML document will not affect the value of success in any way (but you'll be detecting those errors later, in Chapter 4, "Using XML Data in Flash").

As a side note, you really didn't need to call this parameter success. You could've called it anything because it's your function. Flash simply passes a true or false value to the function, and whatever variable you enter as the argument will contain that value.

Step 3: Load the XML

The third step is pretty straightforward, if you have followed along through the two previous steps:

recipeXML.load ("pbj.xml");

The load() method is a simple method of the XML object that takes a filename or URL as a parameter and makes an attempt to load that document.

The onLoad() method is called automatically after the XML is loaded, so you don't need to worry about doing anything after the load(). The onLoad() method handles the rest.

So Where's the XML?

Well, XML uses a complicated structure because it is often used to represent complex data. Because of this, you should be aware that accessing XML from the XML object can also be somewhat complicated. We'll start gently, though.

The onLoad() method is where everything happens, so that's what you'll be modifying right now. Use the same code as before, but replace the original onLoad() definition with this one:

recipeXML.onLoad = function (success) { 
if (success) {
  trace("This is the XML document:");
  trace(this.toString());
    } else {
      trace("Loading Error!")
    }
}

Running that code should give you output that looks like Figure 3.3.

There's not a lot of complicated code here, but what is here performs quite a bit. First, you are actually checking the value of success, and doing something based on that value. If success is false, the document was not loaded successfully and Flash displays the message "Loading Error!". Assuming you have the correct document name, and you're loading from your hard drive (as opposed to a Web server), you shouldn't see this error message at all.

Figure 3.3 The Output window with the new onLoad() method invoking this.toString().

The really interesting bit of code is this line:

trace(this.toString());

The trace() function is the easy part; it's just putting the value of this.toString() in Flash's Output window, as it would with any other value passed to it. The method call this.toString() is the bit of code returning your XML document, though. Here's how it works. onLoad() is a method of recipeXML, so when you use the this keyword, you are referring to recipeXML. In fact, you could've just as easily said recipeXML.toString() instead of this.toString(). In general, XML.toString() (the toString() method for any XML object) returns your XML document in string form. Usually this format isn't useful for anything more than a quick check of your document because the data is not separated in any way. Fortunately, that's all you need right now to make sure your XML is all there.

Moving the Party to the Web

To get this code working on the Web, you're going to need get rid of the calls to the trace() function. In the first frame of your FLA, place a text box, and make it dynamic by selecting Dynamic Text from the Text Options panel. Next, select Multiline from the drop-down list, name it "output," and select the BorderBG check box to make the border and background of the text box show up. You're going to put a good-sized chunk of XML into that box, so resize (both length and width) to match the size of the stage. You'll also overwrite the onLoad() method with a function that sends your XML to the output text box, instead of the trace() function:

recipeXML.onLoad = function (success) { 
if (success) {
  output += "This is the XML document:\n";
   output += this.toString();
    } else {
      output += "Loading Error!";
    }
}

You should expect this new version to look something like Figure 3.4.

Figure 3.4 A Web-based example.

You're now safe to publish your FLA to an HTML file and an SWF file. Uploading the HTML, SWF, and XML files to your Web server will allow you to run the example over the Web.

  • + Share This
  • 🔖 Save To Your Account