Archive for the ‘Data’ Tag

Quick XML attributes parsing

Scenario: you’re loading XML data where the bulk of the fields are stored as node attributes. You now want to transfer these node attributes onto typed objects so that you’ll have compile-time validation of your data integration.

One solution here is to laboriously write an accessor for every XML attribute that sets the value to the corresponding class field… hmmm. Tedious. So, I’ve turned to using a quick solution that works like a charm:

function parseAttributes($obj:Object, $atts:XMLList):Object
{
	for (var j:int=0; j < $atts.length(); j++)
	{
		var $prop:String = $atts[j].name();
		if ($obj.hasOwnProperty($prop))
		{
			if ($obj[$prop] is Boolean) $obj[$prop] = ($atts[j] == "1" || $atts[j] == "true");
			else $obj[$prop] = $atts[j];
		}
	}
	return $obj;
}

An implementation that copies all XML attributes over to a class object looks like this:

var $xml:XML = <myNode name="greg" job="flash"/>;
var $myObj:MyObject = new MyObject();
parseAttributes($myObj, $xml.@*);

The parseAttributes() method receives a object class instance and an XMLList of attributes. It then runs through the XMLList and attempts to set each XML value on the object if a corresponding property exists on the class. Of course, this begs the question of datatyping… How are XML attribute strings set as numeric properties, right? Well, apparently this is a very handy built in feature of the E4X XML parser in ActionScript3. While I’ve never found explicit documentation saying that E4X automatically converts data types, it seem to work perfectly. E4X apparently checks the recipient property’s datatype, and then parses the XML field accordingly.

That said, here are my observations: [int] works (“5″ == 5), [Number] works (“5.321″ == 5.321), and [uint] works (“0xFF0000″ == 0xFF0000). The one exception here seems to be [Boolean]. E4X appears to evaluate all Boolean recipients as “true”, even if the XML value is “0″ or “false”. So, I’ve written a specific catch into the above method to handle Boolean cases. If the recipient property is a Boolean, parseAttributes() will only evaluate the XML field as being true for a value of “1″ or “true”.

Follow

Get every new post delivered to your Inbox.