2011-11-26 67 views
0

夥計們,的Flex-的ActionScript: - XML解析

我有以下在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控件(即按鈕,標籤)。

如何做到這一點?

謝謝。

回答

1
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轉換爲Objects。那麼使用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; 
} 
+0

燦我們在一些arraycollection/dictionary中以名稱 - 值對的形式進行存儲?我無法做到這一點...... –

+0

啊,它很好地轉換xml。然後你有o.Top.Component.getItemAt(index)將是一個對象(這是一個名稱 - 值對基本上) –

+0

你是天才的人! Flex-guru :) ..你的soln工作順利。從我+1和接受這個答案。再次感謝 :) –

0

使用DATAGROUP與返回基於您的XML的性能的的ClassFactory itemRendererFunction。你不需要有一個單獨的步驟先把它變成對象。相反,只是做這樣的事情:

//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/en_US/flex/using/WS77c1dbb1bd80d3836ecbb5ec129ec77b1e1-8000.html#WS94F31173-40D5-4ddd-B7B3-17D02BD57EAF

有關訪問通過E4X的XML的屬性,請參閱 http://dispatchevent.org/roger/as3-e4x-rundown/