FLASH: Recursively parse XML into an array


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;
  }
}

Information and Links

Join the community by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
JAVASCRIPT: Creating objects and methods

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!