XML Data


If the data you are using in Flash becomes complicated, it can be cumbersome to format it in a text file or embed it in an HTML document. This is where XML comes in handy.

Introduction to XML

XML, which stands for Extensible markup language, is a tag-based markup language for structuring data files, especially for passing data between applications. For example, a server-side database application can pass data to a client-side Flash application formatted as an XML file. XML looks similar to HTML because they are both tag-based markup languages. However, XML is more loosely defined. HTML has several predefined tags such as <p> and <h1>. Although specific applications of XML have predefined tags (as in CML for Chemistry), you can create your own tag definitions in generic XML.

An XML document consists of nested elements called nodes. Each pair of beginning tags and closing tags is a node. The elements between an opening tag and its closing tag also make up a node. The nested nodes (the element nodes inside the outer pair of tag nodes) have a parent/child relationship with the outermost node, which is called the base node. A base node is simply the outermost node in an XML structure. The sets of nodes within the parent node are siblings.

The following is an example of a simple XML data structure that uses the same data used in the previous LoadVars example. This is the same data and variable/value pairs, but in a different format. The tags are user-defined, and I designed this particular XML data structure. As you practice with XML, you'll design your own user-defined XML tags.

<myData>     <a>22</a>     <b>12</b> </myData>


Although this example may seem more involved than the LoadVars version, it illustrates how the same data would be formatted. If you wanted to expand this example and add several more data points, the embedded data of the LoadVars version can become unwieldy, whereas the XML format makes the same data easier to read.

XML nodes can have attributes similar to HTML tag attributes, which are variable name/value pairs included inside the brackets. Each node can have several attributes. Nodes must have a closing tag, but a syntax shorthand for empty nodes is to combine the opening and closing tags into a single tag. This is advised when using attributes with no text element for a pair of tags to enclose. In the following, this single tag syntax is used for information on each image. Each node represents a single image. In this shorthand form, the closing slash is what serves as the closing tag, and closes the img node.

<images>     <img title="photo1" url="photo1.jpg" />     <img title="photo2" url="photo2.jpg" />


This XML structure tells Flash that there are two objects in this list of images, and what the title and URL of each object is.

Designing a well-formed XML data structure requires attention to the character of the data itself. If each node has the same set of variables, you might want to use attributes instead of nested nodes because attributes can be parsed quickly by Flash. On the other hand, if your data is more globular in structure and each node has its own internal data structure with unique variables, a nested node structure might be more appropriate.

Now that you have a basic understanding of how to structure data with XML, you are ready to learn how to use it in Flash.

Importing XML Documents

Importing XML documents into your Flash project is a fairly simple process that makes use of the XML() object in Flash. Just as with the LoadVars object, the XML object includes an onLoad event handler that executes when data finishes loading.

You should note that it is important to tell the XML object to ignore the whitespace in the document. Whitespace includes all extra returns or tabs in the document that don't actually contain any data. This way, the XML object works only with nodes and ignores the whitespace formatting, which makes the XML document much easier to read. You do this by setting the ingoreWhite property of the XML object to true, as shown in the following example.

// create a new XML object for the XML formatted data myXML = new XML(); // make sure that whitespace is ignored during parsing myXML.ignoreWhite = true; // function to execute when XML done loading myXML.onLoad = function(){     // do something with data } // load external xml file myXML.load("myData.xml");


Tip

If you use the following code in the myXML.onLoad function, your XML data is traced to the output panel when you run a test:

trace( myXML.toString() );


This is a quick and easy way to test and make sure that your XML data is loading.


Flash's XML object enables you to load XML-formatted data and use its onLoad event handler. The next section discusses some of the other methods of the XML object.

Using XML Data

You can now get your XML-formatted data into Flash. Now what? The XML object has several properties that give you access to the nodes.

  • firstChild returns the first child of a node.

  • hasChildNodes returns true if the node has children.

  • lastChild returns the last child of a node.

  • nextSibling returns the next node from the same generation.

  • nodeName returns the name (in the tag) of a node. If the node is a text node, it returns a 3.

  • nodeType returns 1 if it is a tag node or a 3 if it is a text node.

  • nodeValue returns the content of a text node or null if it is a tag node.

  • parentNode returns the parent node of a node.

  • previousSibling returns the previous node from the same generation.

  • attributes returns the attributes of a tag node, if they have been defined.

  • childNodes returns a list of child nodes. childNodes.length returns the number of elements in the list of child nodes.

After the XML-formatted data is loaded into an XML object in Flash, that's where it lives and you can access it from that object. One way to see that data in the authoring environment is to trace the entire contents of your XML object instance (myXML) to the output window, as in the following example:

trace(myXML.toString() );


Test the movie and you can see all your lovely XML in the output window.

You can also explore your XML object with the debugger's Variables panel. When you play your movie, it presents the information for each node in your XML object (see Figure 14.1).

Figure 14.1. View of node information in the Variables panel of the debugger.


Now would be a good time to look at an example of how to use these properties of the XML object to get access to XML-formatted data. First, however, take another look at the simple XML data structure we created earlier. In the following example, two variable-value data pairs are formatted in XML.

<myData>     <a>22</a>     <b>12</b> </myData>


As you can see, the first node is <myData>. You can get some interesting information about it with ActionScript. For example, you can get its name, even if you didn't know it ahead of time:

// show the name of the XML's first node trace(myXML.firstChild.nodeName);


That's all well and good, but what you really need is a variable name/value pair equivalent to a=22 that you can then use elsewhere in the application. How do you get that? Well, you know that the node named a has a child node, which is a text node with a value of 22. So, in ActionScript, you can write the following:

var a_name:String = myXML.firstChild.childNodes[0].nodeName; trace(a_name);


This should return an output of a. This creates a local variable that holds the name of the node in which you're interested. Next, you could run a conditional to test whether the local variable name is the same as the node name before proceeding:

if(a_name == "a"){     // this is the node we want, continue }


This is not a requirement, but it gives you more ways to manipulate your data after you've gotten it into Flash. I mention it now mainly to illustrate the relationships between the nodes, as well as how to access their data with ActionScript.

Next, you can get the value of the a node's child node and assign it to a local variable (which is also called a):

var a:Number = myXML.firstChild.childNodes[0].firstChild.nodeValue; trace("a = " + a);


When you test this, you should see a = 22 in the output panel.

Look at another simple example, this time with attributes. This time, the goal is to package information about image files, such as the title and URL address of each image in the list. You've seen this example earlier in the chapter:

<images>     <img title="photo1" url="photo1.jpg" />     <img title="photo2" url="photo2.jpg" /> </images>


To keep the code shorter and easier to read, you can give your node paths a name. For example, you can give the myXML.firstChild path the name path. This turns this code

img_0.title = myXML.firstChild.childNodes[0].firstChild.attributes.title;


into the following code:

// save root XML path as local variable var myPath:String = myXML.firstChild; img_0.title = myPath.childNodes[0].firstChild.attributes.title;


This technique is especially helpful when the data structure gets more complicated, with many levels of nested nodes.

To get the image title for the second node, you can use the following:

img_1.title = myPath.childNodes[1].firstChild.attributes.title;


This gives you the next node in the list of images. You can keep track of which node you're on, much as with an array. Both XML nodes and array elements are numbered. The count starts at zero, so the first node is at childNodes[0], the second at childNodes[1], and so on. If you have several images described in an XML file, it would be a good idea to loop through them rather than write out line after line of complicated XML navigation. By using the node count, you can keep track of how many times you need to run a loop that does something with all the nodes describing the images. The following is an example of such a loop:

// get number of images to process var i_max:Number = myXML.firstChild.childNodes.length; // save root path as local variable var path = myXML.firstChild; for(var i=0; i<=i_max; i++){     // save dynamic name as local variable     var img:Object = ["image_" + i];     // save title for this image     img.title = path.childNodes[i].attributes.title;     // save url for this image     img.title = path.childNodes[i].attributes.url; }


Working with XML data in Flash can be a challenge, but the XML object gives you a lot of methods for accessing that data. In the next section, you learn some of the basics of building XML data with Flash.

Building XML Data

If you want to send data out of your Flash file to the server you can build XML data at run-time. In this section, you learn how to build XML data with ActionScript. One of the benefits of this is that you can use XML to format data passed to Flash from a database, create a user interface that enables the end user to edit the data content during run-time, and send the edited data in XML format back to the database.

Imagine you want to build an XML file to hold information for the guest list for a dinner party. Starting simply, you need some basic information for each guest, including his or her name. The XML structure for this data might look something like this:

<guestlist>     <guest>Joe Smith</guest>     <guest>Sally Jones</guest> </guestlist>


To build this XML-formatted data structure from ActionScript, you must first create a new XML object to hold your data as shown in the following example:

guestXML = new XML();


Next, you create a node for your guest list and then attach it to an existing node as follows:

newList = guestXML.createElement("guestlist"); guestXML.appendChild(newList);


To add a node for a guest, you must first create the new node. This new node is the parent node; you can think of it as a wrapper for all the nodes that will contain information about the guest. Next, create a text node for the guest's name. Finally, append the text node to the guest node, which nests the node containing the guest's name inside of the wrapper for the guest's information, as shown in the following example:

// create and append node for guest newGuest = guestXML.createElement("guest"); newText = guestXML.createTextNode("Joe Smith"); newGuest.appendChild(newText);


At this point, the guest node is just hanging out in the XML object and is not yet part of the XML structure. To add the new guest node to the list node, do the following:

newList.appendChild(newGuest);


This process must be done for each guest that you want to add to the XML data.

What if you want to add an attribute to the guest node? For example, imagine you want to include the phone numbers of your guests. No problem. Before appending the newGuest node, add a line similar to the following:

newGuest.attributes.phone = "555-5555"


After your data is in XML format, you can send it back to the server, where it can be stored for future use.

Sending XML Documents to the Server

To send XML-formatted data back to the server, use the send() method of the XML object as shown in the following example:

myXML.send("getxml.cgi");


This sends your XML object to the server. As you can see, XML-formatted data can be passed back and forth from your user interface (built with Flash) and a server-side database.



Special Edition Using Macromedia Studio 8
Special Edition Using Macromedia Studio 8
ISBN: 0789733854
EAN: 2147483647
Year: 2003
Pages: 337

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