Code I/O

A topnotch site

5 Minutes on Adobe Flex – Binding XML to DataGrid

Leave a comment

I’ve been curious to bind XML directly to a data-grid, and here is a way I found to do so.

Assume the following XML data which is defined using attributes as.

var baXml:XML = new XML("<BankAccounts />");
baXml.appendChild(XML('<BankAccount bankName="Bank ABC" accountNumber="12345" />'));
baXml.appendChild(XML('<BankAccount bankName="Bank 123" accountNumber="66666" />'));
baXml.appendChild(XML('<BankAccount bankName="Bank XYZ" accountNumber="77777" />'));

baDG.dataProvider = (xml.BankAccount);

The easiest way to bind this XML directly is better such that I don’t have to build any intermediate arrayCollection or other data structure.

Since we know that the rows are of interest in this scenario, we can bind data directly as data provider elements.

Once it is done, the datagrid uses the XML attribute names directly to render the values

<mx:DataGrid id="baDG" x="25" y="20" width="544" height="156" >
        <mx:DataGridColumn headerText="Bank Name" dataField="@bankName"/>
        <mx:DataGridColumn headerText="Account Number" dataField="@accountNumber"/>

The same is not possible when the XML data is defined as elements.  Lets describe the above data as elements now.

var baXml:XML = <BankAccounts>
        <bankName>Bank ABC</bankName>
        <bankName>Bank 123</bankName>
        <bankName>Bank XYZ</bankName>

Once the elements are defined, the datagrid uses the element names directly to render the values

<mx:DataGrid id="baDG" x="25" y="20" width="544" height="156">
        <mx:DataGridColumn headerText="Bank Name" dataField="bankName"/>
        <mx:DataGridColumn headerText="Account Number" dataField="accountNumber"/>

All of this can be done in just 5 minutes 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s