Using XML and ActionScript with Flex Applications
(Page 1 of 5 )
In this conclusion to a five-part series on using ActionScript to build sophisticated programs in Flex, we will add XML to the equation. It is excerpted from chapter four of the book Programming Flex 2, written by Chafic Kazoun and Joey Lott (O'Reilly, 2007; ISBN: 059652689X). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Creating XML Objects
There are two ways to create XML objects in ActionScript: using XML literals or with the XML constructor. XML literals are useful when you want to define the XML data directly in the code and you know the exact XML data you want to use. The following example defines an XML literal and assigns it to a variable:
var xml:XML = <books>
<book>
<title>Programming Flex 2</title>
<authors>
<author first="Chafic" last="Kazoun" />
<author first="Joey" last="Lott" />
</authors>
</book>
<book>
<title>ActionScript 3.0 Cookbook</title>
<authors>
<author first="Joey" last="Lott" />
<author first="Keith" last="Peters" />
<author first="Darron" last="Schall" />
</authors>
</book>
</books>;
We’ll assume that this is theXMLobject referenced by the remainder of the XML examples in this chapter.
If you aren’t able to define the XML data directly in ActionScript, you can load the data as a string and pass it to theXMLconstructor. In the following example,loadedXMLDatais a variable containing XML data loaded from an external source at runtime:
var xml:XML = new XML(loadedXMLData);
When you use theXMLconstructor, any string data you pass to the constructor is parsed into theXMLobject as XML nodes. By default, Flash Player attempts to
interpret all string data as XML. That means it interprets whitespace (carriage returns, tabs, etc.) as XML nodes. That can cause unexpected results. Therefore, if the XML string data you pass to anXMLconstructor contains extra whitespace (for formatting purposes) that you don’t want interpreted as XML nodes, you should first set the staticignoreWhitespaceproperty totruefor the XML class, as shown here:
XML.ignoreWhitespace = true;
var xml:XML = new XML(loadedXMLData);
Next: Reading XML Data >>
More Flash Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book Programming Flex 2, written by Chafic Kazoun and Joey Lott (O'Reilly, 2007; ISBN: 059652689X). Check it out today at your favorite bookstore. Buy this book now.
|
|