这里是读取 XML 的示例代码(它工作得很好):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init()" horizontalAlign="center">
<mx:Script>
<![CDATA[
import mx.collections.XMLListCollection;
import mx.utils.ObjectUtil;
private var tempXML:XML;
public function init():void{
tempXML = myXML;
txtA.text = myXML.toString();
readXml();
}
public function readXml():void{
var str:String = "";
var myXML:XMLList = new XMLList(myXML);
for each(var node:XML in myXML){
str = str + "action:" + node["action"] + "\n";
for each(var obj2:XML in node.quotes){
str = str + " name:" + obj2.attributes().toXMLString() + "\n";
str = str + " first:" + obj2["first"] + "\n";
str = str + " first:" + obj2["last"] + "\n";
str = str + " quote_num:" + obj2["quote_num"] + "\n";
}
txtB.text = str;
}
}
]]>
</mx:Script>
<mx:XML id="myXML">
<node>
<action>query</action>
<quotes name="Most Quotes">
<first>John</first>
<last>Smith</last>
<quote_num>71</quote_num>
</quotes>
<quotes name="Least Quotes">
<first>Dave</first>
<last>Cook</last>
<quote_num>6</quote_num>
</quotes>
</node>
</mx:XML>
<mx:HBox width="100%">
<mx:TextArea id="txtA" width="400" height="400" />
<mx:TextArea id="txtB" width="400" height="400" />
</mx:HBox>
注意:此代码是在 actionscript 3 中创建的,但也应该适用于您的版本。请尝试并告诉我是否有用,否则我将不得不为您的版本发布代码。请记住,有很多方法可以做到这一点,我发布这种方式是因为可能更简单。
你可以试试这个这里。
请访问此链接以获取更多说明使用 XML
第二版
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init()" horizontalAlign="center">
<mx:Script>
<![CDATA[
import mx.collections.XMLListCollection;
import mx.utils.ObjectUtil;
private var tempXML:XML;
public function init():void{
tempXML = myXML;
txtA.text = myXML.toString();
readXml();
}
public function readXml():void{
var str:String = "";
var quotes:XMLList = myXML.quotes;
str = str + "action:" + myXML["action"] + "\n";
for (var i:int = 0; i < quotes.length(); i++){
str = str + "----quote name:" + XMLList(quotes[i]).attributes().toXMLString() + "\n";
var quotes_child:XMLList = quotes[i].children();
for (var j:int = 0; j < quotes_child.length(); j++){
str = str + "--------" + XML(quotes_child[j]).name() + ":" + quotes_child[j] + "\n";
}
}
txtB.text = str;
}
]]>
</mx:Script>
<mx:XML id="myXML">
<node>
<action>query</action>
<quotes name="Most Quotes">
<first>John</first>
<last>Smith</last>
<quote_num>71</quote_num>
</quotes>
<quotes name="Least Quotes">
<first>Dave</first>
<last>Cook</last>
<quote_num>6</quote_num>
</quotes>
<quotes name="other">
<first>other_first</first>
<last>other_last</last>
<quote_num>other_num</quote_num>
<other_property>other_prop</other_property>
</quotes>
</node>
</mx:XML>
<mx:HBox width="100%">
<mx:TextArea id="txtA" width="400" height="400" />
<mx:TextArea id="txtB" width="400" height="400" />
</mx:HBox>
你可以试试这个这里。
检查在这个新版本中,我使用带有增量变量的“for”语句迭代每个孩子。