Go to content Go to navigation Go to search

XML2Obj for MTASC strict · Tuesday July 25, 2006 by Rudolf Vavruch

I have written a simple ActionScript 2 class that converts a raw XML stream into an Object. The class was written specifically so that it can be compiled with MTASC -strict.

It was inspired by and partially based on Alessandro Crugnola of Sephiroth's XML2Object, and is almost a drop in replacement for it.

I wrote mine because unfortunately Sephiroth's version does not compile with MTASC and I had become attached to how easy it made the handling of XML.

Before using it as a replacement there are two differences to be aware of:

  • The usage has changed slightly:
    var XML2Obj:XML2Object = new XML2Object();
    newXMLObj:Object = XML2Obj.parseXML(XMLStr);
    
  • The attributes return null if a node has no attributes; and it will return [object Object] if the node does have attributes.

I noticed while working with the Sephiroth version that "-"s in XML node names are converted to "_"s in the Object names. In the interests of creating a drop in replacement I added this functionality to my version too.

Download XML2Object.zip for the class and a working example.

Update (2006/07/27): An example of how this can be used. For instance if you have this XML:


<playlist title="Lazy Afternoon">
	<date>2006/07/27</date>
	<track id="1">
		<band name="Rolling Stones"/>
		<title value="Paint It Black"/>
	</track>
	<track id="2">
		<band name="Hedningarna"/>
		<title value="Min Skog"/>
	</track>
	<track id="3">
		<band name="Bomb 20"/>
		<title value="Forever"/>
	</track>
</playlist>

Once you have converted this to an Object and stored it in trackListObj, you can access the data as follows:

Accessing attributes: trackListObj.playlist.attributes.title will return "Lazy Afternoon".

Accessing node data: trackListObj.playlist.date.data will return "2006/07/27"

Accessing nodes with the same name (nodes with the same name are placed into an array): trackListObj.playlist.track[1].band.attributes.name will return "Hedningarna"

Bringing it all together:


var playList:String = trackListObj.playlist.attributes.title;
playList += " (" + trackListObj.playlist.date.data + ")\n";

for (var i:Number = 0; i < trackListObj.playlist.track.length; i++) {
	playList += trackListObj.playlist.track[i].attributes.id + ". ";
	playList += trackListObj.playlist.track[i].band.attributes.name + " - ";
	playList += trackListObj.playlist.track[i].title.attributes.value + "\n";
}

Will create the following output:

Lazy Afternoon (2006/07/27)
1. Rolling Stones - Paint It Black
2. Hedningarna - Min Skog
3. Bomb 20 - Forever

Commenting is closed for this article.