Creating XML Objects


ActionScript 3.0 provides two basic ways to create XML objects: using a constructor or using literal notation. The constructor works just as you would expect:

var xml:XML = new XML();


Optionally you can pass a string to the constructor that you want to parse into XML:

var xml:XML = new XML("<data><value>a</value></data>");


However, using literal notation is often far easier and more readable. The following example shows a simple XML object that is created with literal syntax:

var catalog:XML = <catalog>    <product >       <name>Product One</name>       <price>50</price>    </product>    <product >       <name>Product Two</name>       <price>35</price>    </product> </catalog>;


You can see that literal notation is easier and more readable, especially when you compare the literal notation with the equivalent constructor notation, shown here:

var catalog:XML = new XML('<catalog><product ><name>Product One</ name><price>50</price></product><product ><name>Product Two</name><price>35</ price></product></catalog>');


You can also use literals to declare XMLList objects. When using XMLList literal notation, you should use <></> as the root tag. The following example creates two XML objects named product in an XMLList object:

var products:XMLList = <>    <product >       <name>Product One</name>       <price>50</price>    </product>    <product >       <name>Product Two</name>       <price>35</price>    </product> </>;


Sometimes you'll have a situation in which you need variable values in your XML object. You can achieve this by using curly braces ({}) to surround the variable within the XML literal. The following example shows how you can create a XML object named product using variable values for both name and price:

var productName:String = "Product One"; var productPrice:Number = 50; var product:XML = <product >    <name>{productName}</name>       <price>{productPrice}</price>    </product>;    var catalog:XML = <catalog>    {product}    </catalog>;


Note

The name of the variable product is the same as the first element of the XML object. Although this is not required, we do this for simplicity. If we were to use a different name for the variable, we would treat that variable name as though it were the name of the first element of our XML object. By naming them the same, we minimize confusion.





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