Search Flex Samples

flex Initializing XML variables

You can assign an XML literal to an XML object, as follows:

var myXML:XML =


burger
3.95


fries
1.45




As the following snippet shows, you can also use the new constructor to create an instance of an XML object from a string that contains XML data:

var str:String = "burger"
+ "3.95
";
var myXML:XML = new XML(str);


If the XML data in the string is not well formed (for example, if a closing tag is missing), you will see a run-time error.

You can also pass data by reference (from other variables) into an XML object, as the following example shows:

var tagname:String = "item";
var attributename:String = "id";
var attributevalue:String = "5";
var content:String = "Chicken";
var x:XML = <{tagname} {attributename}={attributevalue}>{content};
trace(x.toXMLString())
// Output: Chicken


To load XML data from a URL, use the URLLoader class, as the following example shows:

import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;

var externalXML:XML;
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("xmlFile.xml");
loader.load(request);
loader.addEventListener(Event.COMPLETE, onComplete);

function onComplete(event:Event):void
{
var loader:URLLoader = event.target as URLLoader;
if (loader != null)
{
externalXML = new XML(loader.data);
trace(externalXML.toXMLString());
}
else
{
trace("loader is not a URLLoader!");
}
}


To read XML data from a socket connection, use the XMLSocket class. For more information, see the XMLSocket entry in the ActionScript 3.0 Language and Components Reference.

0 comments:

Related Flex Samples

Learn Flex: Flex Samples | Flex Video Tutorials Flex Examples