[英]Flex-ActionScript :- XML Parsing
民間,
我在ActionScript中有以下xml
。
var xml:XML = <Top>
<Component>
<type>Button</type>
<id></id>
<width>50</width>
<height>20</height>
<x>0</x>
<y>0</y>
</Component>
<Component>
<type>Label</type>
<id></id>
<width>30</width>
<height>10</height>
<x>0</x>
<y>0</y>
</Component>
</Top>;
現在,我想讀取/解析此xml字符串,然后根據它們各自的屬性生成Flex控件(即Buttons,Label)。
怎么做 ?
謝謝。
import flash.xml.XMLDocument;
import mx.rpc.xml.SimpleXMLDecoder;
public static function xmlToObject(x:XML):Object{
var xmlStr:String = x.toString();
var xmlDoc:XMLDocument = new XMLDocument(xmlStr);
xmlDoc.ignoreWhite=true;
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
return resultObj;
}
我使用此代碼將xml轉換為對象。 然后,使用xml非常簡單。
例如,您的xml如下所示:
var xml:XML = <Top>
<Component>
<type>Button</type>
<id></id>
<width>50</width>
<height>20</height>
<x>0</x>
<y>0</y>
</Component>
<Component>
<type>Label</type>
<id></id>
<width>30</width>
<height>10</height>
<x>0</x>
<y>0</y>
</Component>
</Top>;
和
var o:Object=xmlToObject(xml);
var top:Object=o.Top;
var componentArrayC:ArrayCollection=top.Component;
for each(var cmp:Object in componentArrayC) {
//You would have these properties:
cmp.type;
cmp.id;
cmp.width;
cmp.height;
cmp.x;
cmp.y;
}
將DataGroup與itemRendererFunction一起使用,該ItemRendererFunction根據XML的屬性返回ClassFactory。 您無需執行其他步驟即可首先將其放入“對象”。 相反,只需執行以下操作:
//yourXML is already populated with your XML
var dataSource:XMLListCollection = new XMLListCollection(yourXML.elements);
//yourDataGroup is defined elsewhere
yourDataGroup.dataProvider = dataSource;
有關使用自定義itemRendererFunction的更多信息,請訪問http://help.adobe.com/zh_CN/flex/using/WS77c1dbb1bd80d3836ecbb5ec129ec77b1e1-8000.html#WS94F31173-40D5-4ddd-B7B3-17D02BD57EAF
有關通過e4x訪問XML屬性的信息,請參見http://dispatchevent.org/roger/as3-e4x-rundown/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.