GhostWire Studios - Flash/Flex UI Components Development And Consulting Services
Quality User Interface Controls For Flash Application DevelopmentAspireUI Components

Nov 06 2009

[AS3] Saving XML As Binary

Published by at 7:44 am under Flash,Flash AS3,Tips

This could be useful if you have an external large, verbose XML file which your application must load during run-time. By saving the XML as binary, you can compress the data and get a much smaller file. Of course, the amount of compression you can get depends on the complexity of your data, but it would typically be over 50% (conservative estimate).

Admittedly, having the XML data in compressed binary format contradicts the original intention of using XML in the first place – to allow human-readable data. Therefore, you will have to decide what exactly is important for your application before proceeding. Perhaps having cryptic external data is indeed what you want – allowing data to be externalized so they can be changed without requiring the SWF to be recompiled, and yet would prefer the data to be non-human-readable.


Converting XML To Binary Data (ByteArray)
First, we look at how to store the XML data in a ByteArray. The following code assumes that you already have the XML data stored as a String value in a variable named “xmlData”:

var data:ByteArray = new ByteArray();
data.writeUTFBytes(xmlData); // xmlData is original XML string
data.compress();

And that does it – the XML data is now in compressed binary.


Saving to File
Now that you have the binary data as a ByteArray object, you can save that object to file as raw data. You can do that either by
(i) posting to a server script;
(ii) using AIR API to save to local storage; or
(iii) using Flash Player 10 API to save to local storage.

We will look at (iii), because that is most accessible to every Flash developer. The class you will use is flash.net.FileReference. The FileReference.save() method is available when targeting Flash Player 10 – it allows you to save the data in the FileReference object to a local file.

As a security measure, the save() method will only work in the Flash Player if you call it in response to a user event (for example, MouseEvent.CLICK event). Therefore, you need to create a button, attach a listener to it, and call the save() method in the listener.

function on_buttonClick(evt:MouseEvent):void
{
	var data:ByteArray = new ByteArray();
	data.writeUTFBytes(xmlData); // xmlData is original XML string
	data.compress();
	new FileReference().save(data, "bindata.xml"); // default name "bindata.xml"
}

The save() method will open a native dialog box – choose a file name and location and you will save the XML data in your local filesystem. Notice that you can save the file in the “.xml” extension, but you will no longer get a human-readable XML file – you will see garbage text if you open the file in a text editor because the data is in compressed binary.


Loading Binary XML
You can load the binary file the same way you would a normal XML file:

var ldr:URLLoader	= new URLLoader();
ldr.dataFormat	= URLLoaderDataFormat.BINARY; // ** make sure you do this **
ldr.addEventListener(Event.COMPLETE, on_XML);
ldr.addEventListener(IOErrorEvent.IO_ERROR, on_XML);
ldr.load(new URLRequest(pathToXMLFile));

Therefore, the code for loading is the same as for normal text XML files, except that you need to set dataFormat to URLLoaderDataFormat.BINARY. Even if you end up loading a normal text XML file, the above code will work just fine.


Converting Binary Data To XML
After the binary XML file is loaded, you convert the binary data back to text XML.

var xmlData:XML;
 
function on_XML(evt:Event):void
{
	if (evt.type == Event.COMPLETE)
	{
		var data:* = URLLoader(evt.target).data;
		if (data is ByteArray)
		{
			try
			{
				ByteArray(data).uncompress();
			}
			catch(e:Error)
			{
			}
		}
		xmlData = XML(data);
	}
}

With the code above, your application will be able to handle both text XML and binary XML files. Therefore, this code is something you can use even if you are not currently using XML stored as compressed binary data. If at a later time you decide to compress your XML in binary format, the application will be able to handle it just fine.

In the next post, we will look at a simple tool you can create easily using Flash/ActionScript 3 to load, read, edit and save XML files in compressed binary format.


Note:
The above technique can be used for any text file, not just XML.

pixelstats trackingpixel
Be Sociable, Share!
           

    8 responses so far

    8 Responses to “[AS3] Saving XML As Binary”

    1. Fruitloopon 06 Nov 2009 at 11:14 am

      Very nice, this blog is gettiv extremely useful as a reference now, I have more than once linked it to friends when they have had issues with things like this. Last example was the sound streaming problem. Keep up the good work, it saves people like me a ton of hassle.

      -F

    2. johnon 06 Nov 2009 at 5:18 pm

      sunny, thanks for sharing the tips

      very nice

    3. FlashScope componentson 09 Nov 2009 at 10:09 am

      Thank you for these useful tips!
      Using them any Flash application will be able to handle both text XML and binary XML files.
      Excellent!

    4. benon 12 Dec 2009 at 12:39 am

      iT IS A GREAT TIPS
      BUT HOW ABOUT IF THE XML IS CREATED DYNAMIC FROM DATABASE
      IS THERE A WAY TO COMPRESS THE XML AT SERVER SIDE LEVEL
      THANKS

    5. sunnyon 12 Dec 2009 at 3:23 am

      The compress() method of ByteArray uses standard zlib compression. Correspondingly, the uncompress() method is able to uncompress any zlib compressed data.

      After generating your xml dynamically, you can compress it using zlib compression before sending the data back to Flash.

      For example, in PHP something like the following will work:

      < ?php

      // $xml is the dynamically generated XML, string type

      $contents = gzcompress($xml);
      echo $contents;

      ?>

    6. benon 12 Dec 2009 at 2:32 pm

      Hi Sunny

      Thanks for your info
      It indeed very helpful.

      p.s. the gzcompress method use level 6 as at
      http://php.net/manual/en/function.gzcompress.php

      Best regards,

      Ben

    7. manoon 21 Sep 2010 at 12:02 pm

      Sunny,

      Great Article man…………….really simple and informative. No where i found examples to convert xml to bytearray and vice versa.

      thanks a lot

    8. Porteron 01 Jul 2011 at 4:26 am

      Awesome, simple article. I was just searching if flash compressing XML on compile, and found this. I’m going to have roughly 1MB or so of xml data in a game I’m working on, and would love to shrink that down as it’s rather heavy for level data. Great article!

    Comments RSS

    Leave a Reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word