/** * XML-TO-OBJECT Class * Converts a XML object to an object with XPath-like sub objects * * @author Zeh Fernando * @version 1.0.1 * * 27 Jul 05 (1.0.1) - first version * 19 Ago 05 (1.0.2) - made attributes work with string nodes */ /* TODO * ... */ /* USAGE this.mXML = new XML(); this.mXML.ignoreWhite = true; this.mXML.onLoad = function() { _global.menu = XMLToObject.convert(this); }; this.mXML.load(_global.MENU_XML); EXEMPLO: NOVIDADES NEWS --> _global.menu.menus[0].menu[0].nome_br[0] == "NOVIDADES" (mXML.loaded) */ class zeh.conversion.XMLToObject { /** * No constructor. */ public function XMLToObject() { trace ("This is an static Class and should not be instantiated."); } /** * Conversion function: takes a XML object and returns a dynamic object * * @param xmlObj A loaded and parsed XML object * @return Object A dynamic object */ public static function convert (xmlObj:XMLNode): Object { var newObj = new Object(); var nname; var tNode; var tAttr; debug ("Going forward... "); if (xmlObj.firstChild.nodeValue === null) { // It's a node debug ("It's a node"); for (var i:Number = 0; i < xmlObj.childNodes.length; i++) { tNode = xmlObj.childNodes[i]; debug ("New name: ["+tNode.nodeName+"]"); if (newObj[tNode.nodeName] == undefined) { // Doesn't exist yet, creates array newObj[tNode.nodeName] = new Array(); } // Adding newObj[tNode.nodeName].push (XMLToObject.convert(tNode)); // Creates attributes newObj[tNode.nodeName][newObj[tNode.nodeName].length-1].attributes = new Object(); for (var j in tNode.attributes) { debug (" New attribute: ["+j+":"+tNode.attributes[j]+"]"); newObj[tNode.nodeName][newObj[tNode.nodeName].length-1].attributes[j] = tNode.attributes[j]; } } debug ("Going back..."); return newObj; } else { // It's an string debug ("It's a string: ["+xmlObj.firstChild.toString()+"]"); debug ("Going back..."); newObj._realStringContent_ = xmlObj.firstChild.toString().split("&").join("&").split("'").join("'").split(""").join("\"").split("\r\n").join("\n"); newObj.toString = function() { return (this._realStringContent_); }; return newObj; } } /** * Just traces stuff. Easy to enable/disable */ private static function debug (txt:String): Void { // trace ("[XML2OBJ] " +txt); } }