范例代码:
var xml:XML= <data> <item name="cat" id="1" type="pet" /> <item name="starling" id="1" type="animal" /> <item name="mouse" id="1" type="animal" /> <item name="dog" id="1" type="pet" /> </data>
目的:要得到type为pet的name,用@type属性找,注意写法带圆括号,包含@ .(@type == 'pet')
var xml2:XMLList = xml.item.(@type == 'pet'); for (var i:* in xml2) { trace(i,xml2[i]); }
trace得到
0
1
怎样得到name的值呢?
-->toString......转成字符串,读出来
var xml2:XMLList = xml.item.(@type == 'pet'); for (var i:* in xml2) { trace(i,xml2[i].toString()); }
trace得到
0
1
读不出来?-->撕碎XML,暴力解决!......
var str:String = xml.item.(@type == 'pet').toString(); trace(str); var arr:Array = str.split('\n'); trace(arr.length); for (var i:int = 0; i < arr.length; i++) { var txt:String = arr[i]; txt = String(txt.split(' ')[1]); txt = txt.substring('name="'.length,txt.length - 1); trace(txt); }
trace得到
<item name="cat" id="1" type="pet"/>
<item name="dog" id="1" type="pet"/>
2
cat
dog
神啊,请赐予我力量,奥特曼~~
记住这个:toXMLString()
var xml2:XMLList = xml.item.(@type == 'pet'); for (var i:* in xml2) { trace(i,xml2[i].toXMLString()); }
trace得到
0 <item name="cat" id="1" type="pet"/>
1 <item name="dog" id="1" type="pet"/>
var xml2:XMLList = xml.item.(@type == 'pet'); for (var i:* in xml2) { trace(i,xml2[i].@name); }
trace得到
0 cat
1 dog
收功
package { import flash.display.Sprite; public class XMLtest extends Sprite { public function XMLtest() { var xml:XML= <data> <item name="cat" id="1" type="pet" /> <item name="starling" id="1" type="animal" /> <item name="mouse" id="1" type="animal" /> <item name="dog" id="1" type="pet" /> </data> /*var xml2:XMLList = xml.item.(@type == 'pet'); for (var i:* in xml2) { trace(i,xml2[i]); }*/ /*var xml2:XMLList = xml.item.(@type == 'pet'); for (var i:* in xml2) { trace(i,xml2[i].toString()); }*/ /*var str:String = xml.item.(@type == 'pet').toString(); trace(str); var arr:Array = str.split('\n'); trace(arr.length); for (var i:int = 0; i < arr.length; i++) { var txt:String = arr[i]; txt = String(txt.split(' ')[1]); txt = txt.substring('name="'.length,txt.length - 1); trace(txt); }*/ /*var xml2:XMLList = xml.item.(@type == 'pet'); for (var i:* in xml2) { trace(i,xml2[i].toXMLString()); }*/ var xml2:XMLList = xml.item.(@type == 'pet'); for (var i:* in xml2) { trace(i,xml2[i].@name); } } } }