Sending and Loading XML


XML (eXtensible Markup Language) is a standard for storing and transferring data. Flash Player has built-in support for working with XML data. You can read about working with XML in Chapter 15, "E4X (XML)." In this chapter, we'll focus on how to send and load XML data.

When you send and load XML from Flash Player, it is always converted to a string. That enables you to send and load XML data (as a string) using the same techniques you use to send and load text. To send and load XML, you use the same URLLoader and URLRequest classes you used to send and load text.

Sending XML

When you send XML data, you generally send the raw XML data using HTTP POST. The ActionScript code required to accomplish this task is similar to that for sending variables. However, rather than using a URLVariables object, you simply assign the XML string to the data property of the URLRequest object. You then generally want to set the MIME type of the request using the URLRequest.contentType property. The following example sends an XML string to a PHP script:

var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest("saveSettings.php"); request.contentType = "text/xml"; request.method = URLRequestMethod.POST; request.data = "<settings><email>email@domain.com</email><phone>555-1212</phone></settings>"; loader.load(request);


Loading XML

Loading XML is exactly the same as loading text with one additional step after the data has loaded. The XML constructor allows you to pass it a string that the constructor will parse into the XML object. You can simply pass the value from the data property of the URLLoader object.

var xml:XML = new XML(_loader.data);


Note

You can optionally cast the data as XML rather than passing it to an XML constructor.


Some XML you load might have additional whitespace (carriage returns and tabs) added for human readability. Unless you tell Flash Player to watch for the extra whitespace, it will interpret whitespace as XML elements. That's generally not the desired behavior. The simple solution is to set XML.ignoreWhitespace before parsing the string to the XML object, like this:

XML.ignoreWhitespace = true; var xml:XML = new XML(_loader.data);





Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

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