Using an XML Configuration File for Flex
Okay, if you are a new Flex developer in training and are going to use a configuration file for your appliation, you might be tempted as I was to do it all in Actionscript code using the URLLoader class. While you can do this, it takes a lot of elbow grease to get the timing just right.
My best experience was using the <mx:HTTPService> tag to load the configuration file and process it into the e4x parsing model as shown:
Let's say you have the following configuration file:
-
<?xml version="1.0" encoding="UTF-8"?>
-
<botconfig>
-
<botname>Andy Richards</botname>
-
<picture>andyRichards.gif</picture>
-
<backgroundStyle>insideRoomTablesBed</backgroundStyle>
-
</botconfig>
Now you want to read that in and assign the contents of each node to a configuration settings object:
-
/*
-
ConfigSettings.as
-
ConfigSettings class defines a custom object for
-
parsing a configuration xml file and distributing the
-
nodes to fields of the object so they are easily accessible to
-
the main Flex Application.
-
*/
-
package edu.asu.simlandia {
-
public class ConfigSettings {
-
-
private var _botName:String;
-
private var _botImage:String;
-
private var _backgroundStyle:String;
-
-
private var xmlDoc:XML;
-
public function get botName():String {
-
return this._botName;
-
}
-
public function get botImage():String {
-
return this._botImage;
-
}
-
public function get backgroundStyle():String {
-
return this._backgroundStyle;
-
}
-
public function ConfigSettings():void {
-
this._interactions = new Array();
-
}
-
public function set botName(value:String):void {
-
this._botName = value;
-
}
-
public function set botImage(value:String):void {
-
this._botImage = value;
-
}
-
public function set backgroundStyle(value:String):void {
-
this._backgroundStyle = value;
-
}
-
/*
-
Function responsible for loading the configuration file,
-
parsing it, and assigning the text properties to the
-
configuration object
-
*/
-
public function loadData(xmlData:XML):void {
-
-
this.xmlDoc = xmlData;
-
this.botImage = this.xmlDoc.picture;
-
this.botName = this.xmlDoc.botname;
-
this.backgroundStyle = this.xmlDoc.backgroundStyle;
-
-
-
}
-
-
}
-
}
Use the following MXML code to do it:
-
<mx:Application
-
xmlns:mx="http://www.adobe.com/2006/mxml"
-
layout="absolute" backgroundColor="#CCCC99"
-
creationComplete="configService.send()">
-
<mx:Script>
-
<![CDATA[
-
import edu.asu.simlandia.*;
-
import mx.rpc.events.ResultEvent;
-
-
private var settings:ConfigSettings;
-
private var configXML:XML;
-
-
private function configure(event:ResultEvent):void {
-
settings = new ConfigSettings();
-
settings.loadData(this.configXML);
-
this.botName = this.settings.botName;
-
this.botImage = "images/" + this.settings.botImage;
-
this.styleName = this.settings.backgroundStyle;
-
}
-
-
]]>
-
</mx:Script>
-
-
<mx:HTTPService url="configFile.xml" id="configService" resultFormat="e4x" result="configure(event)"/>
-
</mx:Application>




