将Flash(AS3)数据保存为XML

Bef*_*all 5 xml flash export actionscript-3

几个小时以来,我已经遍布各种各样的互联网,包括Stack Overflow,试图找出一个可以将Flash中的信息保存到XML文件中的可行实例.

我想获取两种不同类型对象的位置,并将每个对象的列表导出为XML.我们称之为物体蝙蝠.

所以,我希望XML看起来像:

<objects>
    <ball xPos=34 yPos=43/>
    <ball xPos=12 yPos=94/>
    <bat xPos=1 yPos=39/>
</objects>
Run Code Online (Sandbox Code Playgroud)

听起来很简单,但我还没有找到一个正确的例子来确切说明AS3代码可以实现这一点.数据在MovieClip的两个向量中,所以我将使用bats [i] .x和bats [i] .y作为输入值.

如何创建此XML,并将其保存在本地查看?谢谢你的任何帮助,这已经证明非常令人沮丧.

div*_*ges 18

在AS3中使用XML非常简单,所以要使用一些代码扩展TheDarkIn1978的答案:

创建XML对象:

var objs:XML = new XML( <objects /> ); // create the <objects /> node

// for your objects
var ball1:XML = new XML ( <ball /> ); // create the <ball /> node
ball1.@xPos = 12; // add 12 as an attribute named "xPos"
ball1.@yPos = 42; // add 42 as an attribute named "yPos"
objs.appendChild( ball1 ); // add the <ball> node to <objects>

// an example of using variables in your xml
var name:String = "something";
var sx:XML = new XML( <{name} /> ); // creates a node <something />
Run Code Online (Sandbox Code Playgroud)

使用TheDarkIn1978到XMLAS3中的课程了解更多信息.

保存文件:

// saving out a file
var f:FileReference = new FileReference;
f.save( sx, "myXML.xml" ); // saves under the name myXML.xml, "sx" being your root XML node
Run Code Online (Sandbox Code Playgroud)

在保存之前压缩XML(使用大型XML文件,这可以节省很多):

// compressing before saving
var f:FileReference = new FileReference;

var bytes:ByteArray = new ByteArray;
bytes.writeUTFBytes( myXML ); // "myXML" being your root XML node
bytes.compress(); // compress it

f.save( bytes, "myXML.xml" );
Run Code Online (Sandbox Code Playgroud)

加载压缩XML,解压缩并检索XML对象:

// uncompressing a compressed xml
var loader = new URLLoader;
loader.dataFormat = URLLoaderDataFormat.BINARY;

// listen for our events
loader.addEventListener( Event.COMPLETE, this._onLoad );
loader.addEventListener( IOErrorEvent.IO_ERROR, this._onFail ); // not shown
loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, this._onSecurityError ); // not shown

private function _onLoad( e:Event ):void
{
    var loader:URLLoader = e.target as URLLoader;

    // get the data as a bytearray
    var ba:ByteArray = loader.data as ByteArray;

    // uncompress it
    try
    {
        ba.uncompress();
    }
    catch ( e:Error )
    {
        trace( "The ByteArray wasn't compressed!" );
    }

    // get our xml data
    myXML = XML( ba );
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个用于压缩/解压缩XML文件的简单工具.如果您有兴趣,可以访问http://divillysausages.com/blog/xml_compressor_uncompressor获取SWF和来源