Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
105
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 22

XML Class Methods

This section explores the methods of the XML class, which are described in the following table:

Method

Return

Description

 

 

 

addRequestHeader()

Nothing

Adds a request header when the XML object is

 

 

requested from the server.

appendChild()

Nothing

Puts a specified node into the root child list of the

 

 

XML document specified.

cloneNode()

XMLNode

Extracts a target XML node and returns it to the

 

object

requesting object.

createElement()

XMLNode as an

Creates an element node with a name supplied

 

XML element

via a string.

createTextNode()

XMLNode as a

Creates a simple string element as a child to the

 

string

object the method is enacted upon.

getBytesLoaded()

Number

Returns the byte amount of the file that has

 

 

loaded into the XML object specified.

getBytesTotal()

Number

Returns the total byte size specified in the header

 

 

of the requested file.

hasChildNodes()

Boolean

Checks whether an XMNode object has child

 

 

nodes.

load()

Nothing

Specifies a target file to load and proceeds to load it.

parseXML()

Nothing

Replaces the current tree with and parses the

 

 

specified string as a new XML document within

 

 

the object the method is enacted upon.

removeNode()

Nothing

Removes the specified node from its parent, and

 

 

removes all child nodes of the specified node.

send()

Nothing

Sends the specified XML object as a document to

 

 

a URL.

sendAndLoad()

Nothing

Sends the specified XML object as a document to

 

 

a URL and specifies a return object to place the

 

 

server reply.

toString()

String

Returns a literal string of the specified XML

 

 

object.

The addRequestHeader() method has two usages:

Set one HTTP request header field (From, for example). Here’s the syntax:

myXML.addRequestHeader(name:String, value:String) : Void

538

Reading XML

Send an array of HTTP request header fields to set, using this syntax:

myXML.addRequestHeader([name1:String, value1:String, name2:String, value2:String]);

: Void

Headers give the server information about the request being sent. Some XML requests such as SOAP require special headers to be recognized. Request headers are most often used to instruct the remote application about how to use incoming data.

The appendChild() method is used for the construction and modification of XML objects. It takes a single parameter, which must be a childNode or String. A String is automatically run against the parseXML method and becomes the nodeValue of the target object. Here’s the appendChild syntax:

myXML.appendChild(childNode:XMLNode);

The cloneNode() method is used for the construction and modification of XML objects. It has a single parameter, a Boolean. Setting the parameter to true clones the specified node and recursively includes all child nodes of the specified node object. Setting the parameter to false copies the specified node, but does not include any child nodes. Here’s its syntax:

myClonedNode = myXML.cloneChild(recursive:Boolean);

The createElement() method is also used for the construction and modification of XML objects. It has a single parameter, which must be a String. The method creates a new XMLNode object with the nodeName specified in the parameter:

myXML.createElement(elementName:String);

The createTextNode() method, used for the construction and modification of XML objects, adds actual text data to an element. It takes a single parameter, a String that is the text to be added. createTextNode() creates a new XMLNode object but does not create an object with a nodeName or bracketed syntax. Following is the method’s syntax:

myXML.createTextNode(myText:String);

The getBytesLoaded() method is most often used to construct a preload bar or percentage-loaded textField. It measures the progress of asynchronous data loading into the object. This method has no parameters. Here’s its syntax:

myXML.getBytesLoaded();

getBytesTotal() is also used to construct a preload bar or percentage-loaded textField, measuring the progress of asynchronous data loading into the object. The method has no parameters. Here is its syntax:

myXML.getBytesTotal();

hasChildNodes() is most often used to stop a recursive XML object tree navigation method. The method has a no parameters and returns a Boolean. Here’s the syntax:

myXML.hasChildNodes();

539

Chapter 22

The load() method is used when sendAndLoad is not required. It has one parameter, a String object defining the target path of the data file to load. Here is its syntax:

myXML.load(path:String, request:String);

The parseXML() method has one parameter, a String object that is well-formed XML. If the XML object that this method is performed upon contains XML data already, the String specified in this method is parsed as XML and replaces any data already in the XML object. Here’s the syntax:

myXML.parseXML(rawXML:String);

The specified String parameter cannot be a remote file. This method does make remote calls.

The removeNote() method is most often used for manipulating an existing XML object in preparation for sending it to another application or socket. It has no parameters. The operation removes the specified node. If the specified node contains child nodes, all child nodes are also removed. Following is its syntax:

myXML.removeNode();

The send() method is very similar to the global getURL method, but automates the task of attaching the object to the POST action. It has two parameters: a String defining the target URL and a String specifying a window destination for the response from the server. If you do not want to leave the Flash application or open a new browser window, use the sendAndLoad method instead. Here’s send()’s syntax:

myXML.send(serverPath:String,windowName:String)

The sendAndLoad() method is identical to the LoadVars object’s sendAndLoad method. It has two parameters: a String defining the target URL (the method automatically attaches the XML object using POST) and an Object in which the server response will be captured. Using this method invokes the load method of the object specified in the second parameter. The object to be loaded is not required to be XML. Any object with a load method can be specified, including private classes. Following is the syntax of sendAndLoad():

myXML.sendAndLoad(serverPath:String, My_objectInWaiting:Object);

The toString() method is helpful in converting childNodes, which are literal strings, to a String object for manipulation. It can be invoked to transform the XML object into a string, which preserves line breaks and retains well-formed XML syntax. This method is automatically invoked when an XML object is directly traced using the trace method. Here’s the syntax for toString(), which has no parameters:

myXML.toString();

Flash cannot create and save external files. XML object methods are often used to construct and manipulate documents for SOAP and RPC procedures. If you must save your XML, you must use either send method to transport the XML to an external application or server method.

The following table describes the XML class properties:

540

 

 

 

Reading XML

 

 

 

 

 

 

 

 

 

Property

Type

Description

 

 

 

 

 

attributes

Object

An object of value pairs defined by attributes of the ele-

 

 

 

ment specified.

 

childNodes

Array

An array of all the children of the object specified.

 

contentType

String

The MIME type associated with the object specified.

 

docTypeDecl

String

The document type definition specified in the document

 

 

 

type node.

 

firstChild

XMLNode

The first node in the list of childNodes of a Node object.

 

ignoreWhite

Boolean

Determines whether white space should be counted as a

 

 

 

node, or whether it should be ignored.

 

lastChild

XMLNode

The last node in the list of childNodes of a Node object.

 

loaded

Boolean

Becomes true when the onLoad event has fired.

 

nextSibling

XMLNode

The next node in the list of childNodes of a Node object.

 

nodeName

String

The string name of the root node of the object specified.

 

nodeType

Number

A number value representing the node type found during

 

 

 

the parse of the specified object.

 

nodeValue

String or Null

If no childNodes are present, and a string value exists,

 

 

 

nodeValue is the string representation of element contents.

 

 

 

Otherwise, the value is Null.

 

parentNode

XMLNode

If a node has a parent, this object references the parent

 

 

 

node of the specified child. Otherwise, the value is Null.

 

previousSibling

XML Node

The previous node in the list of childNodes of a Node

 

 

 

object.

 

status

Number

A list of error codes encountered during parse. If no errors

 

 

 

are found, the value is zero.

 

xmlDecl

String

The document’s XML declaration

XML Event Handlers

The XML object yields two definable event handler methods: onData() and onLoad().

onData()

The onData() event handler method has one parameter, a String. This method fires as soon as all of the data has arrived from a load() or sendAndLoad() call. If this method is defined, the XML object does not call the onLoad() event handler method. Instead, the data that arrives into the object is sent directly to onData() as a raw string. Here’s the syntax:

myXML.onData = function(str:String):Void { trace(str);

};

541

Chapter 22

onData() makes itself useful by overriding the internal document manipulation parse of the XML object. This means that if what you are loading is malformed XML, or not XML at all, you can still access the string information. An example of non-XML data might be a table of wind speeds in space-delimited format. Allowing such a file to attempt to be loaded as XML would produce an error because it would be considered malformed. You can think of the onData object as a sort of bypass, which routes you directly to the return data requested by the load event.

onLoad()

The onLoad() event handler method has one parameter, which must be a Boolean. This method fires as soon as the data loads and has been separated into a tree of XMLNode objects. Defining onLoad() assumes that you believe the return data from the load method will in fact be well-formed XML. The Boolean state communicates whether the data was parsed successfully:

myXML.onLoad = function(success:Boolean):Void { if(success){

trace(this);

}

};

onLoad() is helpful because it automates a few steps into one. It lets you know when an object has loaded and if the load was successful, calls the parseXML() method, and then provides you an access point for examining the resulting XML object.

ignoreWhite: A Special Property

When an XML object parses XML data, by default it interprets white space (tabs, spaces, newlines, and so on) as XML nodes. If you choose not to ignore white space, and you do not expect these spaces to occur, the structure of the resulting XML object might confuse you when objects are not where you expect them. If you want to parse the white space, you do not need to do anything extra. However, if you want Flash to ignore white space when parsing the data, you can assign a value of true to the ignoreWhite property, like this:

myXML.ignoreWhite = true;

Loading External XML Files

In Chapter 21 you learned to create an XML object. Now you can begin using XML. First, though, you need to get through the details of actually loading the file. In the following example, you load the XML file you created in Chapter 21, using onLoad, onData, load, getBytesLoaded, getBytesTotal, and status. You won’t be working with your loaded document just yet. To load XML files, you must be familiar with onLoad and onData.

Try It Out

Load an XML File and Create Event Handlers

1.Create an XML file with your favorite text editor, enter the following XML, and save the file in your work folder as myData.xml:

542

Reading XML

<?xml version=”1.0” encoding=”ISO-8859-1”?> <channels>

<Station identification=”104.1”> <Name>

Rock And Roll Oldies! </Name>

<Desc>

Music great with hot chocolate! </Desc>

</Station>

<Station identification=”98.6”> <Name>

Rock and Roll </Name>

<Desc>

Music for waiting for Godot! </Desc>

</Station>

<Station identification=”102.5”> <Name>

Electronic Madness! </Name>

<Desc>

Arigato Rules! </Desc>

</Station>

<Station identification=”107.9”> <Name>

Electronic Madness 2! <Name>

<Desc>

Thunder Dome! </Desc>

</Station>

</channels>

2.Open a new Flash document and save it in your work folder as xmlLoadSample.fla.

3.Click the first frame in the timeline, open the Actions panel, and enter the following ActionScript code:

var My_XML:XML = new XML(); My_XML.ignoreWhite = true; My_XML.onData = function(str:String) {

trace(str); trace(My_XML.firstChild.firstChild);

}; My_XML.load(“myData.xml”);

4.Test the code by pressing Ctrl+Enter. Verify that the XML document is displayed in the output window and is available as a String called str. Also verify that the second trace fails, so you can see that onData fails to create an accessible XML object tree.

543

Chapter 22

5.Because you know you’re loading an XML file, go ahead and call the parseXML method in the onData function. Here’s how. Close the test SWF, go back to the Actions panel for the first frame of the xmlLoadSample.fla, and modify the existing code to look like the following:

var My_XML:XML = new XML(); My_XML.ignoreWhite = true; My_XML.onData = function(str:String) {

My_XML.parseXML(str); trace(this.firstChild.firstChild);

}; My_XML.load(“myData.xml”);

6.Test the code by pressing Ctrl+Enter. Verify that the XML document has loaded and is accessible as an XML document by verifying the availability of the firstChild.firstChild property. If you are using a different XML file, you might need to change this test path to a valid property.

7.Because you don’t need to access your XML file as a string, abandon your look at the onData method and switch to onLoad, which will automate the parseXML step. Here’s how:

var My_XML:XML = new XML(); My_XML.ignoreWhite = true;

My_XML.onLoad = function(success:Boolean) { trace(this.status);

if (success) {

trace(this.firstChild.firstChild); } else {

trace(“fail”);

}

};

8.Test the code by pressing Ctrl+Enter. Verify that the XML document loaded by verifying the availability of the firstChild.firstChild property.

9.Save your FLA file as xmlLoadSample.fla; you’ll be using it again in a bit.

How It Works

The load function is an asynchronous event. That is, the return value of the load method has an unknown time index. The time is reliant on the speed at which Flash can import the file. If this file had been on the Internet, it might have taken more than a few seconds to load the byte data of the XML file into Flash. By setting an event handler, you’ve allowed the code the flexibility it needs to complete a useful file load.

The other look you had was at onData. You saw that you could, in fact, load a raw text file and disallow Flash from doing anything with it on its own just like the LoadVars object. If you, in fact, need to load data that is not XML and not an ampersand-delimited set of name/value pairs you should use the LoadVars object.

By switching to the onLoad event, you assume you’re loading an XML document. But this has the advantage of sending the event a Boolean telling you whether the file load was successful. The onLoad method also called parseXML all by itself, so you didn’t have to worry about that step. With onLoad you can concentrate on your XML object right away. The other aspect of onLoad is the status property. The status property has a series of error codes that can tell you whether the XML document was malformed and what particular type of error was encountered.

544

 

 

 

Reading XML

 

The errors codes are as follows:

 

 

 

 

 

 

 

Code

Description

 

 

 

 

 

0

File loaded and parsed successfully.

 

–2

A CDATA tag was not closed.

 

–3

The initial XML declaration was malformed.

 

–4

The DOCTYPE declaration was malformed.

 

–5

A comment had no close syntax.

 

–6

An element node was malformed.

 

–7

Out of memory.

 

–8

An attribute was malformed.

 

–9

A start tag had no matching end tag.

 

–10

An end tag had no matching start tag.

 

 

 

 

Measuring Bytes

Chapter 21 mentioned latency and urged you to think about how to handle asynchronous communications. The tools the XML object provides for this are two properties: getBytesLoaded and getBytesTotal. By using some simple math, you can display a percentage of bytes loaded or manipulate a user interface, such as a progress bar.

A Note about Security and Locality

This example assumes you have access to a remote server. If you test the code when both the SWF file and XML file reside on a local computer, the data file will load nearly instantly. Because this is the case, the test code will show 100 percent loaded immediately, which doesn’t allow you to truly test your preload code locally.

For security purposes, to test the code properly in this example, either place the myData.xml file on an HTTP server, or place myData.xml on the same server as xmlLoadExample.swf. You can add an HTML wrapper file for the SWF if you want, but it’s not a requirement. In the example, you are uploading only the XML file to the HTTP server and keeping the SWF file local, so you can be sure that no security issues get in your way as you test the code.

The details of security and why this example requires this limitation are discussed in the “Explaining Cross-Domain Security” section later in this chapter.

Try It Out

Create a Simple Text-Based Pre-loader

For this example, you create a textField object on the stage. You’ll be creating the textField via ActionScript, but you could just as easily create it as a stage object.

545

Chapter 22

1.Upload the myData.xml file from the previous code examples to your favorite server. For purposes of the code example, call this server www.aRemoteServer.com. Replace this string wherever it exists within the code with your own URL.

2.Test the URL of the newly uploaded file. An example URL might be http://www.aRemoteServer

.com/myXMLProject/myData.xml.

3.If you can see the file in a browser, Flash will be able to see the file. Open xmlLoadSample.fla and open the Actions panel. The following ActionScript code should already exist:

var My_XML:XML = new XML(); My_XML.ignoreWhite = true;

My_XML.onLoad = function(success:Boolean) { trace(this.status);

if (success) { trace(this.firstChild.firstChild); } else {

trace(“fail”);

}

}; My_XML.load(“myData.xml”);

4.The change is simple. In the last line, change the target file string to include the server path of the file that now resides on that server. Your code should now look similar to the following:

var My_XML:XML = new XML(); My_XML.ignoreWhite = true;

My_XML.onLoad = function(success:Boolean) { trace(this.status);

if (success) { trace(this.firstChild.firstChild); } else {

trace(“fail”);

}

}; My_XML.load(“http://www.aRemoteServer.com/myXMLProject/myData.xml”);

5.Test your code by pressing Ctrl+Enter. Just as with the initial version, you will see the XML object populate with external data. At this point it might have taken a few moments for the data to load into your object. This is a good thing, because you now understand the power of an asynchronous event handler. You have an opportunity now to add your pre-loader. Close the SWF and go back to the actions with which you’re working.

6.Create a text field with ActionScript so you can have a visual representation of your code results on the stage. To do so, enter the following code before the My_XML constructor:

this.createTextField(“XMLProgress”,this.getNextHighestDepth(),20,20,40,20); this.XMLProgress.border = true;

this.XMLProgress.text = “0%”;

7.Now you need to declare two functions to watch the My_XML object via a setInterval object. Do that by placing the following code after the textField creation code you just added:

getPercentLoaded = function (handle) {

return handle.getBytesLoaded()/handle.getBytesTotal();

};

watchMyXMLLoad = function (handle) {

546

Reading XML

var perc:Number = getPercentLoaded(handle); if (perc>0) {

XMLProgress.text = int(perc*100)+”%”;

}

if (perc == 1) { clearInterval(MyXMLPreloader);

}

};

8.Now you just need to add an interval declaration to kick off a loop event to watch the file load. Place this code just before the load method of the My_XML object:

MyXMLPreloader = setInterval(this, “watchMyXMLLoad”, 10, My_XML);

9.Your final script should look like this:

this.createTextField(“XMLProgress”, this.getNextHighestDepth(), 20, 20, 40, 20); this.XMLProgress.border = true;

this.XMLProgress.text = “0%”; getPercentLoaded = function (handle) {

return handle.getBytesLoaded()/handle.getBytesTotal();

};

watchMyXMLLoad = function (handle) {

var perc:Number = getPercentLoaded(handle); if (perc>0) {

XMLProgress.text = int(perc*100)+”%”;

}

if (perc == 1) { clearInterval(MyXMLPreloader);

}

};

var My_XML:XML = new XML(); My_XML.ignoreWhite = true;

My_XML.onLoad = function(success:Boolean) { trace(this.status);

if (success) { trace(this.firstChild.firstChild); } else {

trace(“fail”);

}

};

var MyXMLPreloader:Number = setInterval(this, “watchMyXMLLoad”, 10, My_XML); My_XML.load(“http://www.aRemoteServer.com/myXMLProject/myData.xml “);

10.Test your movie by pressing Ctrl+Enter. You will see a text field on the stage that reflects the percentage loaded. If your Internet connection is broadband, loading your small test XML file will probably reflect 100 percent almost instantly. If you’d like to see more granular action of the code, try using a modem, or create a new test XML file that is much, much larger.

11.Save the FLA; you’ll be using it again in the next code example.

547