AS2 XML Decompressor

Tuesday 13 July 2004  –  Filed under: Flash  –  No Comments

I recently stumbled upon an interesting method to reduce big XML files for use with Flash. It is based upon the LZ77 algorithm (Lempel-Ziv 1977) and enables you to compress static XML files to 20 / 30% of their original size.

XML is often the weapon of choice when importing data into a Flash client. Unfortunately, the structure versus data ratio is not perfect. A lot of bytes are wasted (traffic-wise) for structural purposes and it would be great if the file sized could somehow be reduced during transfer. Especially when you’re using large files (multi-language apps, large address files, etc)

The method I found on the net was developed by Mattias Stridsman, aka Strille, and consists of a .NET application to compress the XML file and an Actionscript 1 prototype to enable Flash to de-compress the XML file once it has been received.

As I’m strictly using AS2, I wrote an AS2 implementation of his Actionscript 1 prototype. You can use it in an XML wrapper class. The implementation replaces the native XML onData event. By using this replacement, loading compressed and uncompressed files will be completely transparent. Flash will be able to handle both types without any extra coding.

On to the AS2 code:

[as]// This method has been overridden to check for
// compressed data. If found, the data is decompressed
// and then parsed with (native) parseXML. If no
// compressed data is found, parsing commences immediately.

private function onData( inData:String ) : Void {

if (inData != undefined) {

var i:String = inData;

// compressed data found, decompress…
// direct copy of source at http://www.strille.net/tutorials/FlashXMLCompressor/
// except for strict typing of variables and slight optimization of for..loop
if (i.charAt(0) != ‘<’) {

var ecPos:Number = i.indexOf(” “)+1;
var eC:String = i.charAt(ecPos);
i = i.substr(ecPos+1);
var o:String = “”;
var iL:Number = i.length;
var n:Number = 0;
for ( n = 0; n < iL; ++n) {

if (i.charAt(n) == eC) {
var p = i.charCodeAt(n+1)*114 + i.charCodeAt(n+2) - 1610;
var l = i.charCodeAt(n+3)-14;
o += o.substr(-p, l);
n += 3;
} else {
o += i.charAt(n);
}
}

// decompression done, parse xml
parseXML(o);

} else {

// normal XML file found, parse it right away
parseXML(i);
}

// trigger onLoad with true result
onLoad(true);

} else {

// trigger onLoad with false result
onLoad(false);

}
}[/as]

Important: please note the fact that the decompressor attempts to distinguish compressed from uncompressed files by looking at the first character in the XML file. If that’s “<”, it assumes the source is an uncompressed file. So, make sure the first line of your XML file reads: (set the correct encoding type if required)

[xml][/xml]

Enjoy!

Leave a Reply


Recent Articles

Advertisement

Categories