Question

How do you load an XML using a constructor, I need to parse it into an array and I use a custom class Menu.

Here is my code:

class Menu {
 // XML file's filename
 private var xmlFile:String = "menu.xml";
 private var menu:XML;
 private var menuArray:Array;
 private var mainmenu:Array;

 function Menu() {
  menu = new XML();
  menu.ignoreWhite = true;
  menu.load(xmlFile);

  menu.onLoad = function(success : Boolean) : Void {
   if (success) {
    // determine how many chambers there are now
    menuArray = menu.firstChild.childNodes;
    var length:Number = menuArray.length;
    trace(length);

    // dynamic according to number of chambers
    for (var i:Number = 0; i < length; i++) {
     var sublength:Number = menuArray[i].childNodes.length;
     var submenu:Array = new Array();

     // chamber name and link
     var xmlNode:XMLNode = menuArray[i];
     submenu["name"] = xmlNode.attributes.name;
     submenu["link"] = xmlNode.attributes.link;

     // create sub-item for each chamber
     for (var j:Number = 0; j < sublength; j++) {
      var subXmlNode:XMLNode = xmlNode.childNodes[j];

      var item:Array = new Array(subXmlNode.firstChild, subXmlNode.attributes.link);
      submenu.push(item);
     }

     // create an entry for each chamber
     mainmenu.push(submenu);
    }
   }
  }
 }

 function buildMenu():Void {
  //trace(mainmenu);
 }
}

But unfortunately, nothing gets loaded.

Was it helpful?

Solution

Rather than creating a function inside of the constructor, I would make your load handler be a method of your class and just assign the menu.onLoad equal to that method. Otherwise I don't see any real problems, though I do tend to declare any event handlers before I call a method that could trigger that handler (i.e. setup onLoad before you call load). You may also want to add onData to see if you are getting any raw data from the load as well (onData receives one argument - the raw text of the file that was loaded).

OTHER TIPS

I don't think you are creating your mainmenu array. You could amend the code to the following:

menu = new XML();
menu.ignoreWhite = true;
menu.load(xmlFile);

mainmenu = new Array();//add this
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top