Сохранение XML-файла в AS3 возможно

Это не подразумевается как ответ на первоначальный вопрос, но я хотел поделиться кодом тестов, чтобы позволить людям самим проверить два предложенных решения:

require 'benchmark'

s = "one thing, two things, three things, four things"
result = ""

Benchmark.bmbm do |b|
  b.report("strip/split: ") { 1_000_000.times {result = s.split(",").map(&:strip)} }
  b.report("regex: ") { 1_000_000.times {result = s.split(/\s*,\s*/)} }
end

В моей системе (Ruby 2.0.0p247 на OS X 10.8), которая выдает следующий результат:

Rehearsal -------------------------------------------------
strip/split:    2.140000   0.000000   2.140000 (  2.143905)
regex:          3.570000   0.010000   3.580000 (  3.572911)
---------------------------------------- total: 5.720000sec

                    user     system      total        real
strip/split:    2.150000   0.000000   2.150000 (  2.146948)
regex:          3.580000   0.010000   3.590000 (  3.590646)

Эти результаты, конечно, могут варьироваться в зависимости от версий ruby, аппаратного обеспечения и ОС.

8
задан GSerg 14 October 2012 в 21:53
поделиться

3 ответа

, если вы хотите сохранить его локально (на клиентском ПК), вы можете использовать локальный общий объект. См. Этот учебник

3
ответ дан 5 December 2019 в 08:00
поделиться

Извините, ваш вопрос не очень ясен.

Вы спрашиваете, можете ли вы сохранить файл на жесткий диск из компилируемого SWF, написанного на AS3?

Или вы спрашиваете, можете ли вы включить необработанный XML-файл в свой проект AS3 без необходимости записывать его как переменную?

Если вы имели в виду первое, то нет - не без Adobe AIR. Вы можете сохранить данные локально как SharedObject, но не как произвольный файл в файловой системе.

Если последнее, то да - вы должны внедрить файл так же, как если бы вы вставляли другой ресурс (например, изображение или звук). Однако похоже, что во Flash может быть ошибка, из-за которой разобраться, как это сделать, нетривиально.

Эта ссылка может вам помочь.

[Embed(source='../../../../assets/levels/test.xml', mimeType="application/octet-stream")]
public static const Level_Test:Class;

А затем проанализировать XML:

var ba:ByteArray = (new Levels.Level_Test()) as ByteArray;
var s:String = ba.readUTFBytes( ba.length );
xml = new XML( s );

Приносим извинения, если ни один из этих вопросов не является тем, что вы на самом деле задавали.

Ура!

1
ответ дан 5 December 2019 в 08:00
поделиться

I threw this together, and sure enough you can save to .XML using the following as a minimalist example.

package com.hodgedev.xmlcreator
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.utils.ByteArray;
    import flash.net.FileReference;

/**
 * ...
 * @author Brian Hodge (brian@hodgedev.com)
 */
public class Main extends Sprite 
{
    private var _xml:XML;

    public function Main():void 
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);

        //Calling the save method requires user interaction and Flash Player 10
        stage.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseDown);

        _xml= <xml>
              <test>data</test>
              </xml>;
    }
    private function _onMouseDown(e:MouseEvent):void
    {
        var ba:ByteArray = new ByteArray();
        ba.writeUTFBytes(_xml);
        //ba.

        var fr:FileReference = new FileReference();
        fr.addEventListener(Event.SELECT, _onRefSelect);
        fr.addEventListener(Event.CANCEL, _onRefCancel);

        fr.save(ba, "filename.xml");
    }
    private function _onRefSelect(e:Event):void
    {
        trace('select');
    }
    private function _onRefCancel(e:Event):void
    {
        trace('cancel');
    }
}

}

There are some things to note.

  • You require Flash Player 10 to use the save method of the FileReference class.
  • In order to do anything that INVOKES a prompt, Flash requires user interaction like keyboard or mouse input.

In the above I listen for MouseEvent.MOUSE_DOWN on the stage to serve as the USER INTERACTION which is required to invoke the save prompt.

I setup a basic XML structure within the code (this will typically come from and external source and will work fine both ways.

A ByteArray is created and the XML is written to the ByteArray.

The save method of the FileReference class requires a ByteArray and default save name be passed as the two parameters.

I hope this helps.

17
ответ дан 5 December 2019 в 08:00
поделиться
Другие вопросы по тегам:

Похожие вопросы: