2012-08-27 229 views
-1

我有一些数据的XML的..如何分别从每个父节点获取子节点?

<main> 
    <TabNavigator x="27" y="11" width="455" height="376" id="gh" backgroundColor="#A4B6E9"> 
    <NavigatorContent width="100%" height="100%" label="Client" id="clientTab"></NavigatorContent> 
    <NavigatorContent width="100%" height="100%" label="Admin" id="adminTab"></NavigatorContent></TabNavigator> 
    <TitleWindow x="521" y="84" width="377" height="234"> 
     <DataGrid x="0" y="0" width="375" height="163" borderVisible="true" id="details"> 
     <columns> 
      <ArrayList> 
      <GridColumn dataField="Name" id="arrayName"/><GridColumn dataField="Address" headerText="Address"/> 
      <GridColumn dataField="Phone_Number" headerText="Phone_Number"/> 
      </ArrayList> 
     </columns> 
     </DataGrid> 
     <Button x="139" y="167" height="28" label="Export"/> 
    </TitleWindow> 
</main> 

我使用以下用于检索给定XML的孩子的名字代码..

private function urlLdr_complete(event:Event):void{ 
var xmlData:XML=new XML(URLLoader(event.currentTarget).data);      
for each (var t:XML in xmlData.children()) 
{ 
    Alert.show(t.Name); 
} 

但我只得到2名儿童(TabNavigator的和TitleWindow中)。如何我在每个父节点中获得其他孩子吗?我想为每个家长单独的孩子。我怎么才能得到它?

+1

[我如何从Xml数据获取所有子节点?](http://stackoverflow.com/questions/12137607/how-i-get-all-the-children-nodes-from-xml-数据) – Kodiak

+0

同意 - 这是重复的。或者,另一方面,考虑到时间安排,这是重复的。 – JcFx

回答

1

您需要使用递归函数来遍历树。使用跟踪()而不是警报():

private function urlLdr_complete(event:Event):void 
{ 
    var xmlData:XML=new XML(URLLoader(event.currentTarget).data); 
    showNodeName(xmlData); 
} 

private function showNodeName($node:XML):void 
{ 
    // Trace the current node 
    trace($node.name()); 
    if($node.hasChildNodes) 
    { 
     for each (var child:XML in $node.children()) 
     { 
      // Recursively call this function on each child 
      showNodeName(child); 
     } 
    } 
} 

或者,使用E4X后裔()函数:

private function urlLdr_complete(event:Event):void 
{ 
    var xmlData:XML=new XML(URLLoader(event.currentTarget).data); 
    // Trace the root node: 
    trace(xmlData.name()); 
    // And trace all its descendants: 
    for each(var child:XML in xmlData.descendants()) 
    { 
     trace(child.name()); 
    } 
} 

双方应产生相同的结果:

main 
TabNavigator 
NavigatorContent 
NavigatorContent 
TitleWindow 
DataGrid 
columns 
ArrayList 
GridColumn 
GridColumn 
GridColumn 
Button 

我的天堂”经过测试,但我期望内置的后代()函数更高效。

+0

这就是我一直在寻找的......你是最棒的,非常感谢你! –

+0

不客气。但下次发布一个问题可能是一个好主意 - 这与其他问题非常相似:http://stackoverflow.com/questions/12137607/how-i-get-all-the-children-nodes-from -xml-data最好编辑和改进你的原始问题,而不是发布另一个类似的问题,如果它没有得到答案。 – JcFx

相关问题