Home > Articles > Web Services > XML

Getting Your Feet Wet in Flash-XML Integration

  • Print
  • + Share This
This sample chapter provides your first steps into Flash-XML integration by providing an example that 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.
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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020