ActionScript 3 AS3加载外部XML文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ActionScript 3 AS3加载外部XML文件相关的知识,希望对你有一定的参考价值。
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLLoaderDataFormat;
import flash.system.Capabilities;
import flash.text.TextField;
import flash.text.TextFormat;
public class Main extends Sprite
{
private var _xmlPath:String = "data.xml";
private var _xmlHasLoaded:Boolean = false;
private var _xmlLoader:URLLoader;
private var _xmlRequest:URLRequest;
private var _dataXml:XML;
private var _id:String;
private var _title:String;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init():void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
loadDataXml(_xmlPath);
}
private function loadDataXml($xmlPath:String):void
{
trace("loadDataXml("+$xmlPath+")");
_xmlLoader = new URLLoader();
_xmlLoader.dataFormat = URLLoaderDataFormat.TEXT;
_xmlLoader.addEventListener(Event.COMPLETE, onXmlLoader_COMPLETE);
_xmlLoader.addEventListener(IOErrorEvent.IO_ERROR , onXmlLoader_IO_ERROR);
_xmlRequest = new URLRequest();
if (Capabilities.playerType == "External") {
_xmlRequest.url = $xmlPath;
} else {
_xmlRequest.url = $xmlPath + "?rand=" + Math.random();
}
try {
trace("try: urlLoader.load("+_xmlRequest.url+")");
_xmlLoader.load(_xmlRequest);
} catch (error:Error) {
trace("catch: Unable to load XML data.");
}
}
private function onXmlLoader_COMPLETE(event:Event):void
{
trace("onXmlLoader_COMPLETE()");
_xmlLoader.removeEventListener(Event.COMPLETE, onXmlLoader_COMPLETE);
_xmlLoader.removeEventListener(IOErrorEvent.IO_ERROR , onXmlLoader_IO_ERROR);
_xmlHasLoaded = true;
try {
_dataXml = new XML(event.target.data);
trace(_dataXml.toString());
start();
} catch (err:TypeError) {
trace("Could not parse text into XML");
trace(err.message);
}
}
private function onXmlLoader_IO_ERROR(event:IOErrorEvent):void
{
trace("onXmlLoader_IO_ERROR("+event+")");
trace("event.text: "+String(event.text));
}
private function start():void
{
// Do something here
_id =_dataXml.title.@id;
trace("_id: "+_id);
_title = _dataXml.title;
trace("_title: "+_title);
var tfmt:TextFormat = new TextFormat();
tfmt.size = 22;
tfmt.font = "Arial";
var tf:TextField = new TextField();
tf.width = 549;
tf.height = 399;
tf.wordWrap = true;
tf.multiline = true;
tf.defaultTextFormat = tfmt;
tf.condenseWhite = false;
tf.border = true;
tf.htmlText = _title;
addChild(tf);
}
}
}
////////////////////////////////////////////////////////
// The XML file in this situation would
// look like this and be called 'data.xml'
//
// <?xml version="1.0" encoding="utf-8"?>
// <root>
// <title id="001"><![CDATA[Hello World]]></title>
// </root>
//
////////////////////////////////////////////////////////
以上是关于ActionScript 3 AS3加载外部XML文件的主要内容,如果未能解决你的问题,请参考以下文章
ActionScript 3 AS3 - 停止缓存的外部加载文件