[英]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.