Binding XML attribute to a DataGrid column

Most binding examples work with a flat XML structure. However, in most cases the format of the data attribute will not work directly with Flex components. I was looking for a way to bind XML attributes to a DataGrid in Flex.

XML:
    <Vehicles>
<Vehicle id=”1″ status=”SUCCESS”>
<car type=”ford”>my car</car>
</Vehicle>
<Vehicle id=”2″ status=”SUCCESS” />
</Vehicles>

MXML code:
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.collections.XMLListCollection;

[Bindable]
private var respStr:String = “<Vehicles><Vehicle id=”1″ status=”SUCCESS”><car type=”ford”>my veh</car></Vehicle><Vehicle id=”2″ status=”SUCCESS” /></Vehicles>”;
[Bindable]
private var xmlObj:XML

private function LoadData():void {
xmlObj = new XML(respStr);
dGrid.dataProvider = xmlObj.Vehicle;
}
private function carType(item:Object, column:DataGridColumn):String {
if (item.car.@type == undefined)
{return null;}
else
{return item.car.@type;}
}
]]>
</mx:Script>
<mx:DataGrid x=”76″ y=”104″ id=”dGrid”>
<mx:columns>
<mx:DataGridColumn headerText=”ID” dataField=”@id”/>
<mx:DataGridColumn headerText=”Status” dataField=”@status”/>
<mx:DataGridColumn headerText=”Value” dataField=”car”/>
<mx:DataGridColumn headerText=”Type” labelFunction=”carType”/>
</mx:columns>
</mx:DataGrid>

<mx:Button label=”Load Data” click=”LoadData()” />

</mx:Application>

Most binding examples work with a flat XML structure. However, in most cases the format of the data attribute will not work directly with Flex components. I was looking for a way to bind XML attributes to a DataGrid in Flex. XML:     <Vehicles> <Vehicle id=”1″ status=”SUCCESS”> <car type=”ford”>my car</car> </Vehicle> <Vehicle id=”2″ status=”SUCCESS” />…

Leave a Reply

Your email address will not be published. Required fields are marked *