20.11.载入XML

问题
我想从XML文档中或服务端脚本产生的XML中读取XML数据
解决办法
使用URLLoader.load( ) 方法且设置dataFormat属性为DataFormat.TEXT读取数据,通过complete事件处理函数转换载入的数据为XML实例
讨论
ActionScript 3.0中发送和读取数据由新的URLLoader及其相关类完成,读取XML也没有什么特殊的地方。

读取XML文件的步骤如下:首先创建URLLoader实例以简单文本形式读取数据,其dataFormat 属性必须设置为DataFormat.Text,监听并添加complete事件处理函数,看下面的例子演示:
+展开
-ActionScript
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.util.*;
public class LoadXMLExample extends Sprite {
public function LoadXMLExample( ) {
var loader:URLLoader = new URLLoader( );
loader.dataFormat = DataFormat.TEXT;
loader.addEventListener( Event.COMPLETE, handleComplete );
loader.load( new URLRequest( "example.xml" ) );
}
private function handleComplete( event:Event ):void {
try {
// Convert the downlaoded text into an XML instance
var example:XML = new XML( event.target.data );
// At this point, example is ready to be used with E4X
trace( example );
catch ( e:TypeError ) {
// If we get here, that means the downloaded text could
// not be converted into an XML instance, probably because
// it is not formatted correctly.
trace( "Could not parse text into XML" );
trace( e.message );
}
}
}
}

上面的例子中之所以用try...catch 块,是考虑到读取的数据有可能不是XML 格式数据,TypeError 异常就是不能成功转换为XML 实例时抛出的。

加支付宝好友偷能量挖...


评论(0)网络
阅读(72)喜欢(0)flash/flex/fcs/AIR