Flex初始化时加载外部XML
Flex初始化时加载外部XML
2010年07月21日
Flex初始化时加载外部XML配置文件
Flex项目中经常需要同服务器进行数据交互,可以将服务器访问地址写到到XML配置中,在Flex初始化时读取到内存。省去因服务器地址变化而重新编译Flex程序的麻烦。
1、添加XML配置文件(config.xml) http://localhost:2286/HttpService.aspx http://localhost:2286/HttpService1.asp x http://localhost:2286/HttpServi ceViewBook.aspx false 2、在Flex主程序preinitialize时加载些配置文件 3、加载配置文件的MyDomain类 package com.Domain { import com.Tool.MyXml; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; public class MyDomain { public function MyDomain() { } public static var IsHasInitServer:Boolean = false; //主程序是否已经将服务配置加载完成 public static var HttpServiceName:String = ""; public static var HttpServiceName2:String = ""; public static var HttpServiceViewBook:String = ""; public static var IsTest:Boolean = false; public static function init(configXMLURL:String):void { var xmlUrl:String = configXMLURL if(xmlUrl == null) xmlUrl = "config.xml"; //加载 var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.TEXT; loader.addEventListener(Event.COMPLETE,xmlLoaded); var request:URLRequest = new URLRequest(); request.url = xmlUrl; loader.load(request); } private static function xmlLoaded(event:Event):void { var xml:XML = XML(event.target.data); var myxmltool:MyXml = new MyXml(); var obj:Object = myxmltool.xmlToObject(xml); try { MyDomain.HttpServiceName = String(obj.root.domain["httpServcie"]); MyDomain.HttpServiceName2 = String(obj.root.domain["httpServcie2"]); MyDomain.HttpServiceViewBook = String(obj.root.domain["httpServiceViewBook"]); var strIsTest:String = String(obj.root.domain["isTest"]); if(strIsTest.indexOf("true") != -1) MyDomain.IsTest = true; MyDomain.IsHasInitServer = true; trace(String(obj.root.domain["httpServcie"])); } catch(e:Event) { //Alert.show("网站维护中..., 请您稍候访问"); trace("================================ "); trace("配置文件出错,请检查配置文件是否正确!"); trace("配置文件格式为:Your HttpService"); trace("================================ "); return; } } }} 4、读取XML的MyXml类 package com.Tool { import flash.xml.XMLDocument; import mx.rpc.xml.SimpleXMLDecoder; public class MyXml { public function MyXml() { } private static var xmlDoc:XMLDocument; public static var decoder:SimpleXMLDecoder; public function xmlToObject(value:XML):Object { //var xmlStr:String = value.toXMLString(); var xmlDoc:XMLDocument = new XMLDocument(value.toXMLString()); var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true); //var resultObj:Object = decoder.decodeXML(xmlDoc); return decoder.decodeXML(xmlDoc); } } } 读取XML的可以使用其它方法
这样主程序中再使用HttpService等就可以直接从MyDomain中读取相应的服务URL地址