Home > Articles > Graphics & Web Design > Dreamweaver & Flash

📄 Contents

  1. Chapter 3 : Getting Your Feet Wet
  2. The Basics of Flash's XML Object
  3. Summary
This chapter is from the book

This chapter is from the book

The Basics of Flash's XML Object

Now that you've successfully imported XML into Flash, it's time to learn a bit more about Flash's handling of XML and, more specifically, the XML object.

All XML-based applications share the need to read in XML from a file and extract the meaningful data and data structures from that file. The portion of the application that does this is called the XML parser. Flash is no exception, and considering the size of the Flash plug-in, its built-in XML parser is quite sophisticated. XML.load() automatically starts the parser, and the parser reads through the XML, dividing up the individual elements, attributes, and other components, and puts them in the XML object (recipeXML, in our case).

After that XML object is created and fully populated with the XML data, Flash automatically calls the onLoad() method, and continues through any remaining ActionScript before moving on to the next frame in the timeline. It's good to understand this, because Flash's XML parser can be slow as documents get larger. We will discuss remedies for this problem later in Chapter 8, "Performance and Optimization," but for now, it's enough to realize that your Flash movie will freeze while Flash parses your XML for you. It will probably be unnoticeable on reasonably modern computers when the XML document is relatively small, but it can become noticeable under less-than-optimal conditions (like huge XML documents on slow computers).

Also, the XML parser in Flash is a non-validating parser. What this means is that although Flash can read a DTD, it does not do anything whatsoever with that information. It does not check your XML to ensure that it's valid, and it makes no attempt to determine whether your XML conforms to the document type. On the plus side, it can determine whether your document is well formed. The XML object has a simple property called status that returns the value 0 if there are no errors, and returns another number matching a corresponding error code if an error did occur. In the "XML.status" section of Appendix A, "The XML Object," we'll go into more detail on the subject of error codes. For now, however, it's enough to know that you want a value of 0 for your status, otherwise something has gone wrong. To see the status property for the loaded document, add the following line before the call to toString():

output += "The status is "+this.status+"\n";

Running this code now should produce results similar to Figure 3.5.

Figure 3.5 this.status (notice the status line at the top).

Whitespace Stripping

As we explained in Chapter 2, "The Details of XML," whitespace is irrelevant to most XML applications, and Flash-XML applications are no exception. Whitespace certainly makes things easier on human eyes, but to Flash it is a nuisance that just sucks up processing power. To make matters worse, there are different versions of the Flash 5 plug-in floating around that have different features for handling whitespace in XML.

If your user has revision 5.0.41 or later of the Flash 5 plug-in, you can just set a global property called XML.ignoreWhite to true with this simple code:

XML.ignoreWhite = true;

Unfortunately, to make this work for all plug-in versions, you still have to detect users' revision number and proceed appropriately. If they have an earlier player version, you will still need an alternative method of whitespace stripping.

For that reason, it usually makes more sense to write some ActionScript to remove the whitespace. You can do this a number of ways, as you'll see in Chapter 4 (the easiest method is to keep the whitespace out of the XML document altogether, but that would make it difficult for humans to read and edit). It is important to do it, though, or Flash will store the spaces, tabs, carriage returns, and line feeds in your XML as character data, which can cause all sorts of problems when you are trying to get information from a specific element.

The Flash parser treats whitespace as character data, as it would if you had normal text between two tags. That's not necessarily the wrong approach, but it certainly isn't useful for normal use, when you don't care about the superfluous space. It's also essential that you make the first character in your XML document a non-whitespace character. If you don't, the parser will think you want your root node to be that whitespace text data. Of course, this is illegal XML, so it will generate errors.

Keep these things in mind during the following examples. You're going to have to remove the whitespace from your recipe example so that it doesn't interfere. Here's what it should look like:

<?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> 

It's not very readable from our point of view, but to Flash, it's perfect.

Knowing Nodes

XML elements are represented as nodes in a Flash object. For the most part, anytime we talk about XML nodes, we're talking about the representation of XML elements in Flash's XML object. In fact, there's an undocumented object in Flash called XMLnode that is much like the XML object, although it is made to represent a subelement rather than an entire XML document (which, as you've seen, is represented by the XML object). The XML object contains a single XMLnode object, just as an XML document contains a single root element. In Flash ActionScript, the root element of an XML document is represented as the firstChild of the object. In our example, recipeXML.firstChild is the XMLnode that contains the root element <recipe>. To verify this, change your onLoad() method to the following:

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

The addition of the nodeName property lets you know the name of the node. You should get something that looks similar to Figure 3.6.

Figure 3.6 Sample output with the addition of this.firstChild.nodeName (notice the nodeName at the top).

Taking this one step further, you can get the name of the root element's first subelement simply by saying

output += "First SubElement: "+this.firstChild.firstChild.nodeName;

The output from this line is, of course, name, which is the element that names your recipe and contains the text peanut butter and jelly sandwich.

To start browsing other subelements, or children of the root element, you need to use the nextSibling property of the XMLnode object, which is actually a reference to another XMLnode. The reference points to the XMLnode that is the next child of the two nodes' common parent. For example, try this:

output += "fC-fC-nextSibling: "; 
output += this.firstChild.firstChild.nextSibling.nodeName;

Now the output should include fC-fC-nextSibling: ingredient_list because the firstChild is <recipe>, <recipe>'s firstChild is <name>, and <name>'s nextSibling is <ingredient_list>. Keep in mind that although <ingredient list> is a child of <recipe>, it isn't the firstChild; <recipe> is. You can have only one firstChild, of course (because other ones wouldn't be first—they'd be second or third, and so on). This is one of the more complicated aspects of the XML object in Flash; Figure 3.7 shows a diagram that will help you understand how the XML elements are accessed by using Flash's XMLnode objects.

Figure 3.7 This is a tree diagram of the XML and XMLnode objects.

You can access any node in an XML object using these firstChild and nextSibling properties, so feel free to experiment, and make sure you understand how this naming works. For the most part, nodes are Flash's representation of the elements of an XML doc. One exception is for character data such as the text you find between tags in an XML document. Flash treats that text as nodes, too. It's a little confusing at first, but in the long run, it's nice to have all the XML data accessible through the single XMLnode object.

XMLnodes that contain text data instead of elements (we'll call them "text nodes" to make the distinction) are accessible by firstChild and nextSibling, too, because they are XMLnodes in their own right. It's pretty simple once you get used to it, but there is one little snag that often confuses people new to the technology: If you want to get the text from a text node in Flash, use nodeValue instead of nodeName. You might be used to using nodeName to get the information from XMLNodes, but if it is an XMLnode containing text data, not element data, you need to use nodeValue to retrieve that data. To see it in action, try this quick example in your onLoad() function:

output += "fC-fC-fC: "+this.firstChild.firstChild.firstChild.nodeValue;

That line should add the string peanut butter and jelly to your output listing. Figure 3.8 shows a diagram similar to Figure 3.7, but with text elements mapped out, too. Notice the way nodeValue is used for text nodes and nodeName is used for elements.

Figure 3.8 This is a tree diagram showing the use of XMLnode.nodeName (for recipe) and XMLnode.nodeValue (for peanut butter and jelly sandwich).

Aside from nodeName and nodeValue, another important property of XMLnode objects to learn is nodeType. Checking the nodeType of an XMLnode in Flash returns the value 1, denoting an XML element, or the value 3, denoting character data. Using our beloved PB&J recipe, you can see in Figure 3.9 exactly what the nodeTypes are for each of the nodes. This is pretty straightforward, but it's a useful property, as you'll see later.

The primary goal of using XML in Flash is to extract the information from the XMLNode objects; to determine whether you should be using nodeName or nodeValue, you need to know the nodeType. Later chapters go into more depth on extracting information from nodes when you don't necessarily know the type, so this property will be very handy then.

Figure 3.9 This is a tree diagram showing the use of XMLNode.nodeType.

The last important source of information is in the attributes of your elements. The XMLNode object also contains an attributes property, which is implemented as an associative array. If you've dealt with arrays before, associative arrays are even easier. Instead of referencing each object in the array by numeric keys, you can use literal keys. If you want to find how much peanut butter to use in the PB&J example, you need to target the first ingredient (peanut butter) at recipeXML.firstChild.firstChild.nextSibling.firstChild. Next, you access the quantity attribute in the attributes array with attributes ["quantity"] (see Figure 3.10).

Figure 3.10 This is a tree diagram showing the use of XMLNode.attributes[].

Putting this altogether, you can show the value 2 tbsp with the following amendment to your onLoad() function:

output += "pb quantity: ;
output += this.firstChild.firstChild.nextSibling.firstChild.attributes
["quantity"];

The attributes array is not the only array in the XMLNode object, either. Another array called childNodes, shown in Figure 3.11, can save you from writing long object strings with nextSibling, such as this.firstChild.nextSibling. nextSibling.nextSibling.

Figure 3.11 This is a tree diagram showing the use of XMLnode.childNodes[].

Quite often, you need to get an arbitrary child of an XMLnode, and using the childNodes array can get that information for you more directly. Here's a quick example:

output += "third ingredient:";
output += this.firstChild.firstChild.nextSibling.childNodes[2].firstChild.
nodeValue;

This code shows you the text in the third ingredient, bread. The first part, this.firstChild.firstChild.nextSibling, refers to the <ingredient_list> element, which you know has three elements: the three ingredients. The keys of the childNodes array start at 0 for the first child, and increase from there. So firstChild is at childNodes[0], firstChild.nextSibling is at childNodes[1], and firstChild.nextSibling.nextSibling is at childNodes[2]. Therefore, accessing childNodes[2] indicates that you want the third child node. You can continue further with firstChild.nodeValue, too, to make sure you get the value of the text in the element you've targeted with the childNodes array. The output, of course, is bread.

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