Code I/O

A topnotch WordPress.com 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:columns>
        <mx:DataGridColumn headerText="Bank Name" dataField="@bankName"/>
        <mx:DataGridColumn headerText="Account Number" dataField="@accountNumber"/>
    </mx:columns>
</mx:DataGrid>

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>
    <BankAccount>
        <bankName>Bank ABC</bankName>
        <accountNumber>12345</accountNumber>
    </BankAccount>
    <BankAccount>
        <bankName>Bank 123</bankName>
        <accountNumber>66666</accountNumber>
    </BankAccount>
    <BankAccount>
        <bankName>Bank XYZ</bankName>
        <accountNumber>77777</accountNumber>
    </BankAccount>
</BankAccounts>;

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:columns>
        <mx:DataGridColumn headerText="Bank Name" dataField="bankName"/>
        <mx:DataGridColumn headerText="Account Number" dataField="accountNumber"/>
    </mx:columns>
</mx:DataGrid>

All of this can be done in just 5 minutes 🙂

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s