|
|
||
|
|
||
|
|
||
In this chapter, you
Thats it for the theory behind XML
documents. The rest of the book will focus on using Flash with XML
documents. In Chapter 4, Ill look at the XML
class and we'll create a photo gallery and MP3 player driven by XML
data. Later in the book, well cover the data
|
|
||
|
|
||
|
|
||
In the earlier chapters, you learned about XML and some of the
This chapter will introduce you to the
XML
classthe most common way to work with XML
documents in Flash. In Chapters 8 and 9, well
look at another way to work with XML documents: by using data
If youre not familiar with object-oriented
programming, the
The XML class was introduced in Flash 5, and since that time, the ActionScript associated with it hasnt changed significantly. The XML class became a native object in Flash 6, which increased its speed compared with Flash 5. The XML class stores XML content in document trees within Flash. The class allows you to
Create new XML documents or
Load external XML documents
Modify XML content
Send XML information from Flash
The XML class includes methods and properties to work with XML document trees. Youll also use a related class, the XMLNode class, which allows you to work with specific nodes in an XML document tree. You can find a summary of the methods, properties, and events of both classes in the tables at the end of this chapter.
When we create a new XML object from the XML class, we call the object an instance of the class, and the process of creating the object is known as instantiation . One way to view the difference is to see the XML class as a template that you use to create XML objects.
Well start this chapter by learning how to load an external XML document into a Flash XML object. Well look at how you can extract information from the document tree so you can add it to your Flash movie. You could do this with either a physical document saved with an .xml file extension or a stream of XML information. If youre working with an information stream, you can load XML content generated by a PHP, ColdFusion, or ASP.NET server-side page or from a web service. Well cover web services in Chapter 9.
|
|
||
|
|
||
|
|
||
The process of loading an XML document into Flash involves the following steps:
Create an XML object.
Specify what happens after the XML document loads, that is, identify a function to deal with the loaded XML information.
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
The following code
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
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
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
var myXML = new XML();
myXML.ignoreWhite = true;
myXML.onLoad = functionName;
myXML.load("http://localhost/webfolder/filename.aspx");
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
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
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
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.
|
|
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 .
|
|
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.
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.
When you load an external XML document into Flash, its possible that it may not be well formed. Remember that well-
The document contains one or more elements.
The document contains a single root element, which may contain other nested elements.
Each element
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
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
ˆ 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
ˆ 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
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
<?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.
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:
Create the XML object.
Set the ignoreWhite property to true.
Specify the name of the function that will deal with the loaded XML document.
Load the XML document.
Within the load function, test whether the XML file has loaded successfully.
Display the document tree with a trace action to check the loaded contents.
Well work through an example to
Exercise 1: Loading an external XML document
|
|
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 .
Create a new Flash movie and click frame 1 on the Timeline.
Save the document in the same folder as the address.xml file.
Add the following code into the Actions panel. You can
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);
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.
Figure 4-2:
The Output window displaying XML content
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.
Figure 4-3:
The Output window displaying an error message
In the previous exercise, we loaded the file
address.xml
into Flash. We
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
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");
|
|
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
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
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