如何在actionscript或as3中迭代嵌套的XML数据?

时间:2015-09-14 13:15:24

标签: xml actionscript-3 flash flex

这是我的XML数据

public var treeData:XML =  <item name="vCenter Server" type="Server">
   <item name = "Datacenter" type="Datacenter" checked="false" moid="datacenter-85">
        <item name = "Cluster1" type="ClusterComputeResource" checked="false"  value="one" moid="cluster-85">
            <item  name = "Host1" ctype="Cluster1" type="HostSystem" checked="false" value="one" moid="hostystem-85"/>
            <item  name = "Host2" ctype="Cluster1" type="HostSystem" checked="false" value="one" moid="hostystem-86"/>
        </item>
         <item name = "Cluster2" type="ClusterComputeResource" checked="false" value="two" moid="cluster-86">
            <item name = "Host3" ctype="Cluster2" type="HostSystem" checked="false" value="two" moid="hostystem-87"/>
            <item name = "Host4" ctype="Cluster2" type="HostSystem" checked="false" value="two" moid="hostystem-88"/>
        </item>
        <item name = "Host 3" type="HostSystem" checked="true" moid="hostystem-89"> </item>
        <item name = "Host 4" type="HostSystem" checked="false" moid="hostystem-90"> </item>
   </item>  
</item>;

如何在actionscript中迭代嵌套的xml数据并显示警报:

如果选中为真,则显示您已选择

如果选中错误,则显示您未在任何项目中选择

我已经完成了以下代码,但它无效。

override public function isValid():Boolean
{
    if(treeData == null){
        Alert.show("Empty tree")
        return false;
    }
    else {
        for each(var item:XML in treeData)
        {

            for each(var item:XML in server.item.item)
            {
                if(item.@checked != true)
                {
                    Alert.show("You have not selected any item");
                    return false;
                }
                else if(item.@checked == true){
                    Alert.show("You have selected item");
                    return true;
                }
            }
        }
        return true;    
    }

}

我在复选框功能

上迭代这个xml

1 个答案:

答案 0 :(得分:2)

You can simplify life using E4X ( ECMAScript for XML ) to get the number of the selected items from your xml content like this :

trace(
    xml.*.(@checked == 'true').length() +       // level : 1 ( Datacenter ), gives : 0
    xml.*.*.(@checked == 'true').length() +     // level : 2 ( Cluster1, Cluster2, Host 3, Host 4 ), gives : 1
    xml.*.*.*.(@checked == 'true').length()     // level : 3 ( Host1, Host2, Host3, Host4 ), gives : 0
);      
// gives : 1

For more details about working with XML in AS3, take a look here.

Hope that can help.