AS2 | Programming

Recursively convert XML into multidimensional array (AS2)

This is a code snippet I wrote awhile back that recursively works through an XML file and converts it from XML into a multidimensional array. This was from the days before E4X was a part of ActionScript, and as such this is an ActionScript 2.0 example, so it may not be as useful as it once was. But nonetheless, maybe someone will find it of use. Here it is (usage example is at the end):

//recursive function to convert an XML file to an array
function XMLtoArray(node:XMLNode, arr:Array):Array{
	var nodelen:Number = node.childNodes.length;//number of children nodes within a particular node
	var resultValue:Array = [];//result of a recursive call to this function
	var count:Number = 0;//index number of the current node relative to its siblings
	node = node.firstChild;
	//loop through node children
	for (var i=0; i < nodelen; i++) {
		//if the first child of that node does not have children
		//create an associative array with the node name equal to the node value
		if (node.firstChild.hasChildNodes() == false){
			arr[node.nodeName] = node.firstChild;
			//else node has more nodes inside, make a recursive call to walk down the XML tree
			arr[count] = [];
			resultValue = XMLtoArray(node, arr[count]);
			if (resultValue != undefined){
				arr.push(resultValue);//push result into array
		//when loop is on its last iteration return the compiled array
		if (i == (nodelen-1)){
			return arr;
		node = node.nextSibling;
	return undefined;
var imgXML:String = "<cat><img><filename>1.jpg</filename><caption>cap1</caption></img><img><filename>2.jpg</filename><caption>cap2</caption></img></cat>";
var xmlArray:Array = XMLtoArray(new XML(imgXML), new Array());
//xmlArray[0] goes into first node <cat>
//xmlArray[0][0] goes into second node <img>
//xmlArray[0][0]["caption"] retrieves contents of <caption>cap1</caption>
//outputs the filename of the second image