MLNTN

Maniacal musings of a pixel perfectionist

Archive for the ‘Flash’ Category

Iterating through objects, the easy way

Posted by Jared On May - 8 - 2008

Objects in any ECMAScript language (Javascript, Actionscript, Jscript, etc) are very powerful for – among other things – storing data. However, getting some information out of these objects can be a hassle sometimes.

I ran into this issue recently and wrote some cool little handlers for objects. The following methods can be used to iterate through an array manually. I wrote them for Actionscript, but they certainly work for Javascript – although I’d suggest one small modification (shown later). Read the rest of this entry »

Recursively parse XML into an array

Posted by Jared On December - 1 - 2007

Flash does not make it easy to handle XML. I’ve used some really bad code to help me parse arrays until I came up with this. It doesn’t handle elements of the same name at the same level, but it can probably be modified to do so.

var myParsedXML = new Array();

var myXML = new XML();
myXML.ignoreWhite = true;
myXML.onLoad = function(success) {
  if (success) {
    parseXML(myXML);
  }
};

myXML.load("data.xml");
function parseFile(xmlData) {
  var mainXMLElement = xmlData.firstChild.childNodes;
  for (var i = 0; i < mainXMLElement.length; i++) {
    myParsedXML.push(intoArray(mainXMLElement[i]));
  }
}

function intoArray(xml_element){
  var xml_array = new Array();
  if (xml_element.hasChildNodes()) {
    for (var cn = 0; cn < xml_element.childNodes.length; cn++) {
      if (xml_element.childNodes[cn].nodeType == 1) {
        xml_array[xml_element.childNodes[cn].nodeName] = xml_element.childNodes[cn].firstChild;
        if (xml_element.childNodes[cn].attributes) {
          xml_array[xml_element.childNodes[cn].nodeName].attributes = xml_element.childNodes[cn].attributes;
        }
      }
      else {
        xml_array[xml_element.childNodes[cn].nodeName] = intoArray(xml_element.childNodes[cn]);
      }
    }
    return xml_array;
  }
}