Parsing XML: good practice

With the new XML class of AS3 parsing XML has become much easier than before but it’s still time consuming writing the functions to parse the xml data.

Having done that over and over again I thought about a nice interface to use when retreiving data from XML and one day I will create a Class to include all this XML util functions (keeping in mind the little but really useful tip that my colleague Alec posted on his blog about Boolean values)

So say you want to retrieve an attribute of an xml element as a Number.

I would usually cast the value to Number then check that that value is compatible with what I expect and if not assign a default value, for example:


var DEFAULT_ID_VALUE:Number = 1;

var xmlExample:XML = <element id="7"/>;

var id:Number = xmlExample.@id;

if (isNaN(id))
    id = DEFAULT_ID_VALUE;

so why not encapsulate that logic in a function like:

private function convertToNumber(value:String, def:Number = 0):Number
{
    var tmp:Number = Number(value);
    if (isNaN(tmp))
    {
        trace(">> ERROR: cannot convert ", value, " to Number. Using default "+def);
        tmp = def;
    }
    return tmp;
}

then if we refactor the previous example we’ll have

var DEFAULT_ID_VALUE:Number = 1;

var xmlExample:XML = <element id="7"/>;

var id:Number = convertToNumber(xmlExample.@id, DEFAULT_ID_VALUE);

you can then see how you could create a xml utility class that contains conversion functions
for all the types.

This entry was posted in AS3, Flash and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
blog comments powered by Disqus