2011-07-08 47 views
1
public class loadXML extends Sprite 
{ 
    public var xmlFileName:String; 
    public var urlL:URLLoader = new URLLoader(); 
    public var urlR:URLRequest; 
    public var xml:XML = new XML(); 

    public function loadXML(xmlS:String):void 
    { 
     xmlFileName = xmlS; 
     urlR = new URLRequest(xmlFileName);    
     urlL.addEventListener(ProgressEvent.PROGRESS, onProgressAction); 
     urlL.addEventListener(Event.COMPLETE, onLoadedAction); 
     urlL.addEventListener(IOErrorEvent.IO_ERROR, errorAction); 
     urlL.load(urlR);    
    } 
    public function onLoadedAction(e:Event):void 
    { 
     xml = XML(e.target.data); 
     //trace(xml); 
    }  
    public function onProgressAction(e:ProgressEvent):void 
    { 
     //trace("loading xml"); 
    } 
    public function errorAction(e:IOError):void 
    { 
     trace(e.toString()); 
    } 
} 
} 

//主类加载XML文件使用AS3

package 
{ 
import com.loadXML; 
import flash.display.Sprite; 

public class xmlFileView extends Sprite 
{ 
    public var xmlData:loadXML; 
    public function xmlFileView():void 
    { 
     init(); 
    } 
    private function init():void 
    { 
     xmlData = new loadXML("list.xml"); 
     var xmlF:XML = XML(xmlData); 
     //trace(xmlF.video[0].path); 

    } 
} 

}

在这里,我实例化loadXML的类。但我无法访问xml,y?我怎么能做到这一点?

这是我的XML文件。

<?xml version="1.0" encoding="iso-8859-1"?> 
<videos> 
    <video> 
     <path>video1.flv</path> 
    </video> 
    <video> 
     <path>video2.flv</path> 
    </video> 
    <video> 
     <path>video3.flv</path> 
    </video> 
    <video> 
     <path>video4.flv</path> 
    </video> 
</videos> 

回答

3

你有XML有面色不喜欢XML :) 这里应该怎么看起来像reffering的trace(xmlF.video.path[0]);

<?xml version="1.0" encoding="utf-8" ?> 
<data> 
    <video> 
     <path>video1.flv</path> 
     <path>video2.flv</path> 
     <path>video3.flv</path> 
     <path>video4.flv</path> 
    </video> 
</data> 

UPDATE

你不能这样做:

xmlData = new loadXML("list.xml"); 
var xmlF:XML = XML(xmlData); 

,因为加载内容需要时间,并且脚本不会等待加载完成。

如果要实现这一目标,你需要做以下的方法:在loadXML的类编辑功能 :

public function onLoadedAction(e:Event):void 
{ 
    xml = XML(e.target.data); 
    // dispatch event when the XML has been loaded and xml value is defined. 
    dispatchEvent (new Event (Event.COMPLETE)) 
} 
在xmlFileView类编辑

private function init():void 
{ 
    xmlData = new loadXML("list.xml"); 
    // listen for loading completed 
    xmlData.addEventListener (Event.COMPLETE, handleXMLLoaded); 
} 

private function handleXMLLoaded (e:Event):void 
{ 
    var xmlF:XML = xmlData.xml 
    trace(xmlF.video.path[0]); 
} 
+1

eddited答案,希望我会帮你的。 –

+2

@Jevgenij Dmitrijev'私人函数handleXMLLoaded(e:Event):void {}'* – Taurayi

+1

修正了小错误,否则很好的答案 – shanethehat