我建议您将此 XML 转换为 XMLList 并在遍历其元素时将列添加到数据网格。
默认情况下,您应该确定一组空的数据网格列。在我的示例中,如果您不这样做,您将获得两倍的列,因为网格可以根据数据提供者的结构自动定义列。
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600" creationComplete="init(event)">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
import mx.events.FlexEvent;
private var columnList:XMLList;
[Bindable]private var data:ArrayCollection = new ArrayCollection([
{first_name:"John", last_name:"Busch", region_name:"CA"},
{first_name:"Mike", last_name:"Harris", region_name:"DC"},
{first_name:"Linda", last_name:"Brucks", region_name:"CA"}]);
protected function init(event:FlexEvent):void
{
loadXML();
}
private function loadXML():void
{
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onXMLComplete);
loader.load(new URLRequest("assets/config/rumpy.xml"));
}
private function onXMLComplete(evt:Event):void
{
var xmlData:XML = XML((evt.currentTarget as URLLoader).data);
columnList = xmlData.Column;
var cols:Array = list.columns;
for each (var item:XML in columnList)
{
var adgc:AdvancedDataGridColumn = new AdvancedDataGridColumn(item.@dataField);
adgc.headerText = item.@headerText;
cols.push(adgc);
}
list.columns = cols;
}
]]>
</fx:Script>
<mx:AdvancedDataGrid id="list" x="10" y="10" dataProvider="{data}" width="360" height="120">
<mx:columns/>
</mx:AdvancedDataGrid>
</s:Application>
//rumpy.xml
<Columns>
<Column id="first_name" headerText="First Name" dataField="first_name"/>
<Column id="regionName" headerText="Region" dataField="region_name"/>
<Column id="lastname" headerText="Last Name" dataField="last_name"/>
</Columns>