0

类示例:

package {

    import flash.events.*;
    import flash.net.*;

    public class XmlLoader extends EventDispatcher{

        private var _xmlList:XMLList;

        public function XmlLoader(xmlPath:String){
            var xmlUrlRequest:URLRequest = new URLRequest(xmlPath);
            var xmlUrlLoader:URLLoader =  new URLLoader(xmlUrlRequest);
            xmlUrlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
        }

        private function xmlLoaded(e:Event):void{
            e.currentTarget.removeEventListener(Event.COMPLETE, xmlLoaded);
            var xml:XML = new XML(e.currentTarget.data);
            this._xmlList = xml.*;
            dispatchEvent(new Event(Event.COMPLETE));
        }

        public function getXmlList():XMLList{
            return this._xmlList;
        }

    }
}

类使用的一个例子是:

var menuXmlList:XmlLoader = new XmlLoader("pt/menu.xml");
menuXmlList.addEventListener(Event.COMPLETE, printList);

function printList(e:Event):void{
    trace(e.currentTarget.getXmlList());
}

这将打印出 xml 文件的内容。如何在类外访问 xmlList 的节点?

4

1 回答 1

0

我会稍微修改一下加载器公共类 XmlLoader extends EventDispatcher{

        private var _xml:XML;

        public function XmlLoader(xmlPath:String){
            var xmlUrlRequest:URLRequest = new URLRequest(xmlPath);
            var xmlUrlLoader:URLLoader =  new URLLoader(xmlUrlRequest);
            xmlUrlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
        }

        private function xmlLoaded(e:Event):void{
            e.currentTarget.removeEventListener(Event.COMPLETE, xmlLoaded);
            _xml = new XML(e.currentTarget.data);
            dispatchEvent(new Event(Event.COMPLETE));
        }

        public function getXml():XML{
            return this._xml;
        }

    }
}

然后我将像这样访问节点。

var menuXmlList:XmlLoader = new XmlLoader("pt/menu.xml");
menuXmlList.addEventListener(Event.COMPLETE, printList);

function printList(e:Event):void{
    var myXML:XML = (e.currentTarget.getXml());

    var children:XMLList = myXML.children();
    var child:XML;

    for each(child in children)
    {
         trace("Node name: "+child.name()+" -- value: "+String(node));
    }

    // for and xml like
    // <root>
    //     <node1>
    //           <subnode>abc</subnode>
    //           <subnode>def</subnode>
    //           <subnode>ghi</subnode>
    //     </node1>
    //     <node2>
    //           <subnode>123</subnode>
    //           <subnode>456</subnode>
    //           <subnode>789</subnode>
    //     </node2>
    // </root>
    //
    // to access all subnodes inside node 2 use
    //
    // var list:XMLList = xml.node2.subnode;

}
于 2012-12-06T14:43:40.430 回答