Displaying XML data in a DataGrid

by Peter deHaan on July 26, 2007

in DataGrid, XML, XMLListCollection

OK, hopefully this example is a bit more interesting than a few of my previous ones. Today’s handy tip comes in the form of loading and embedding an XML file in our Flex application at compile-time (as opposed to dynamically loading at run-time, which we’ll save for a future example), and displaying that information in a DataGrid control.

The following example loads an XML file at compile-time using the mx:XML and displays the information in a DataGrid:

View cuePoints.xml

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<FLVCoreCuePoints version="1">

    <CuePoint>
        <Time>0</Time>
        <Type>event</Type>
        <Name>slide1</Name>
        <Parameters>
            <Parameter>
                <Name>id</Name>
                <Value>value</Value>
            </Parameter>
        </Parameters>
    </CuePoint>

    <CuePoint>
        <Time>5000</Time>
        <Type>event</Type>
        <Name>slide2</Name>
        <Parameters>
            <Parameter>
                <Name>param1</Name>
                <Value>value1</Value>
            </Parameter>
            <Parameter>
                <Name>param2</Name>
                <Value>value2</Value>
            </Parameter>
        </Parameters>
    </CuePoint>

    <CuePoint>
        <Time>20000</Time>
        <Type>event</Type>
        <Name>slide3</Name>
    </CuePoint>

</FLVCoreCuePoints>

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/07/26/displaying-xml-data-in-a-datagrid/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">

    <mx:XML id="tempXML"
            source="assets/cuePoints.xml" />

    <mx:XMLListCollection id="cuePointXMLList"
            source="{tempXML.CuePoint}" />
    <mx:XMLListCollection id="parametersXMLList"
            source="{dataGrid.selectedItem.Parameters.Parameter}" />

    <mx:Script>
        <![CDATA[
            private function parametersLabelFunction(item:Object, column:DataGridColumn):String {
                return item.Parameters.Parameter.length();
            }

            private function numericSortCompareFunction(objA:Object, objB:Object):int {
                var itemA:Number = parseInt(objA.Time.text()) as Number;
                var itemB:Number = parseInt(objB.Time.text()) as Number;

                if (itemA > itemB) {
                    return 1;
                } else if (itemA < itemB) {
                    return -1;
                } else {
                    return 0;
                }
            }
        ]]>
    </mx:Script>

    <mx:VBox>
        <mx:DataGrid id="dataGrid"
                dataProvider="{cuePointXMLList}"
                width="100%"
                rowCount="{cuePointXMLList.length + 1}">
            <mx:columns>
                <mx:DataGridColumn id="timeCol"
                        dataField="Time"
                        headerText="Time (ms):"
                        sortCompareFunction="numericSortCompareFunction" />
                <mx:DataGridColumn id="typeCol"
                        dataField="Type"
                        headerText="Type:" />
                <mx:DataGridColumn id="nameCol"
                        dataField="Name"
                        headerText="Name:" />
                <mx:DataGridColumn id="parametersCol"
                        dataField="Parameters"
                        headerText="Parameters:"
                        labelFunction="parametersLabelFunction" />
            </mx:columns>
        </mx:DataGrid>

        <mx:DataGrid id="parametersDataGrid"
                dataProvider="{parametersXMLList}"
                width="100%"
                visible="{parametersXMLList.length > 0}"
                rowCount="{parametersXMLList.length + 1}">
            <mx:columns>
                <mx:DataGridColumn id="parameterNameCol"
                        dataField="Name"
                        headerText="Parameter Name:" />
                <mx:DataGridColumn id="parameterValueCol"
                        dataField="Value"
                        headerText="Parameter Value:" />
            </mx:columns>
        </mx:DataGrid>
    </mx:VBox>

</mx:Application>

View source is enabled in the following example.

In case you’re curious, the sample XML document in question comes from a Quick Start I wrote for the Flash CS3 release, “Flash Quick Starts: Using the Adobe Flash CS3 Video Encoder“.

{ 25 comments… read them below or add one }

1 neox2 January 15, 2008 at 11:42 am

Hi, how can i refresh data?

Reply

2 Business Minded May 25, 2008 at 8:16 am

Somehow, I can’t view the flash video. Could you please check into it?

Also, I tried the above code and it didn’t load for me.
var itemA:Number = parseInt(objA.Time.text()) as Number;
var itemB:Number = parseInt(objB.Time.text()) as Number;

Reply

3 peterd May 25, 2008 at 8:07 pm

Business Minded,

The previous video doesn’t display any video at all. It simply displays an XML packet in a Flex DataGrid control.
If you want to display a video you need to use the VideoDisplay control, or use the NetStream, NetConnection, and Video classes.

Peter

Reply

4 Aaron S. October 16, 2008 at 8:00 am

Hi There,

Thanks for the tutorial, it works great. Im wondering if its possible to change the data on the Fly.

for example, creating a FileReference variable and then using the fileRef.browse(); to browse for the .xml file you want to populate the grid with.

Any ideas?

Thanks – your site rocks.

Reply

5 peterd October 17, 2008 at 1:06 am

Aaron S.,

I’ve never tried that, but I’m guessing it should work. I have an example of the FileReference class’s new load() method at http://blog.flexexamples.com/2008/08/25/previewing-an-image-before-uploading-it-using-the-filereference-class-in-flash-player-10/

This code is fairly untested (I only quickly checked it locally, not from a remote webserver), but this may help get you started:

<?xml version="1.0" encoding="utf-8"?>
<FxApplication name="DefineFont4_cff_test"
        xmlns="http://ns.adobe.com/mxml/2009">
    <layout>
        <BasicLayout />
    </layout>

    <Style>
        VGroup {
            left: 10;
            right: 10;
            top: 10;
            bottom: 10;
        }
    </Style>

    <Script>
        <![CDATA[
            private var fileRef:FileReference;

            private function button_click(evt:MouseEvent):void {
                var xmlFileFilter:FileFilter = new FileFilter("XML files (.xml)", "*.xml");

                fileRef = new FileReference();
                fileRef.addEventListener(Event.SELECT, fileRef_select);
                fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
                fileRef.browse([xmlFileFilter]);
            }

            private function fileRef_select(evt:Event):void {
                fileRef.load();
            }

            private function fileRef_complete(evt:Event):void {
                var len:int = fileRef.data.length;
                var str:String = fileRef.data.readUTFBytes(len);
                var dataXML:XML = new XML(str);
                textArea.text = dataXML.toXMLString();
            }
        ]]>
    </Script>

    <VGroup>
        <Button id="button"
                label="Load file..."
                click="button_click(event);" />
        <TextArea id="textArea"
                width="100%"
                height="100%" />
    </VGroup>

</FxApplication>

Peter

Reply

6 Derek Basch January 21, 2009 at 10:53 pm

If your XML data contains namespaces, you will need to use a labelFunction:

<a href=”http://blog.flexexamples.com/2008/12/10/displaying-dynamically-loaded-xml-in-a-datagrid-control-in-flex/>http://blog.flexexamples.com/2008/12/10/displaying-dynamically-loaded-xml-in-a-datagrid-control-in-flex/</a>

Reply

7 cool February 16, 2009 at 5:10 am

Hi

Is there any way we can show xml data in any text box, area box in flex….
actually my requirement is i have to show XML in text box, the way it comes on IE, Mozilla if i directly access the XML e.g + and -

Please guide…

Reply

8 Peter deHaan February 17, 2009 at 8:34 am

cool,

I’m sure there is, but I haven’t played with it. I think what you’d want to do is find a way to parse the XML and display it in a Tree control, which would give you open/close buttons.

Peter

Reply

9 Bala March 25, 2009 at 9:59 am
10 Flex Freelancer March 25, 2009 at 10:41 pm

I am a flex developer based in Bangalore.
I always read your articles. Can you tell me if we can read an XML or CSV file lying on the User PC, in an AIR application.
Basically I need to convert CSV or XML to ArrayCollection.
Thanks,
Rahul.

Reply

11 Anonymous March 31, 2009 at 11:57 pm

@ Rahul..
Yes.. u can read any file located in ur/user’s pc.. Just add file:/// to the path.. Ex file:///C:\XML\XYZ.xml

Reply

12 Flex developer April 1, 2009 at 12:17 am

@rahul
You can access the files in your pc in this way..file:///C:\XML\XYZ.xml

Reply

13 Flex developer April 1, 2009 at 12:20 am

I have a data grid in my application and the data provider is something like
dataProvider=”{XMLlist.(@attribute == “XXX”).elementname}”.

It says data binding will not be able to detect assignments to attribute.
Can someone please help me on this?

Reply

14 Prashant June 24, 2009 at 3:37 am

I want to take a single value from xml in a variable. I’m taking record in dataset (C# code in VS 2008) and returning it in xml format I can fill the grid in flex but if I need to check single value from the xml format than what should I do……?

Reply

15 Peter deHaan June 24, 2009 at 11:15 pm

Prashant,

Well, XML is a pretty broad topic (and usually semi-specific to your exact XML packet/problem in question), but this may help you get started:

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        initialize="init();">

    <mx:Script>
        <![CDATA[
            private var theXML:XML;

            private function init():void {
                theXML = <root someAttribute="Prashant" someDate="09/29/2008">
                            <node id="001" name="Node 1" value="1" bool="true">(1) The quick brown fox jumps over the lazy dog</node>
                            <node id="002" name="Node 2" value="2" bool="false">(2) The quick brown fox jumps over the lazy dog</node>
                        </root>;

                /* Get the root node's someAttribute attribute. */
                var name:String = theXML.attribute("someAttribute").toString();
                lbl1.text = name;

                /* Get the root node's someDate date string and convert it into a Date object. */
                var dat:String = theXML.attribute("someDate");
                lbl2.text = new Date(dat).toDateString();

                /* Get the first "node" node's id attribute. */
                var childID1:Number = theXML.node[0].@id;
                lbl3.text = childID1.toString();

                /* Get the first "node" node's text. */
                var str1:String = theXML.node[0].text();
                lbl4.text = str1.toString();
            }
        ]]>
    </mx:Script>

    <mx:VBox>
        <mx:Label id="lbl1" />
        <mx:Label id="lbl2" />
        <mx:Label id="lbl3" />
        <mx:Label id="lbl4" />
    </mx:VBox>

</mx:Application>

Peter

Reply

16 pavithra July 27, 2009 at 11:53 pm

hello,
I am very new to flex.
i am trying to display data from xml to data grid(followed your example), but it is not happening.

my xml file is as below:

Tool1
10.77.7.174
Grant Control
Steeve

Mac
Katie

Please help me out to display this xml info into the datagrid.

Thanks,
Pavithra.

Reply

17 pavithra July 27, 2009 at 11:55 pm

sending the xml file again:

Tool1
10.77.7.174
Grant Control
Steeve

Mac
Katie

Reply

18 Peter deHaan July 28, 2009 at 6:45 am

pavithra,

You need to change your < chars to &lt; and your > to &gt; to get the raw XML/MXML code to appear on the site.

Sorry,
Peter

Reply

19 Kerstin October 3, 2009 at 1:21 am

Hello,

With my XML I get numeric values, money. The money value comes always thith two decimal points.

123456
My Artikel
10.00

So I want to see two decimal points at all times, even when they would be zero (eg. 1,234.00)

But in the Datagrid only displayd 10 (without .00)

How can I change this?

Thank you,
Kersitn.

Reply

20 Kerstin October 3, 2009 at 1:23 am

part of the XML:

123456
My Artikel
10.00

Reply

21 Kerstin October 3, 2009 at 1:25 am

OK!
< money > 10.00< /money >

Reply

22 Peter deHaan October 3, 2009 at 7:54 am

@Kerstin,

The following example uses an XML data provider but maintains the correct number of decimal places (but I’m using the Flex 3.4 SDK, maybe something was different in earlier builds, or maybe you’re loading an external XML file):

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
 
    <mx:XMLList id="xmlDP" xmlns="">
        <item>
            <id>123456</id>
            <name>My Artikel</name>
            <money>10.00</money>
        </item>
        <item>
            <id>123457</id>
            <name>My Artikel2</name>
            <money>1234.00</money>
        </item>
    </mx:XMLList>
 
    <mx:DataGrid id="dGrid" dataProvider="{xmlDP}">
        <mx:columns>
            <mx:DataGridColumn dataField="id" />
            <mx:DataGridColumn dataField="name" />
            <mx:DataGridColumn dataField="money" />
        </mx:columns>
    </mx:DataGrid>
 
    <mx:Label id="sdkVer" selectable="true" initialize="sdkVer.text = mx_internal::VERSION;" />
 
</mx:Application>

But back to the question at hand… If you want to format a number to have two decimal places, you can use the Number class’s toFixed() method to format to X number of decimal places, as seen in the following example:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
 
    <mx:Script>
        <![CDATA[
            import mx.controls.dataGridClasses.DataGridColumn;
 
            private function money_labelFunc(item:Object, col:DataGridColumn):String {
                return parseFloat(item.money.text()).toFixed(2);
            }
        ]]>
    </mx:Script>
 
    <mx:XMLList id="xmlDP" xmlns="">
        <item>
            <id>123456</id>
            <name>My Artikel</name>
            <money>10.00</money>
        </item>
        <item>
            <id>123457</id>
            <name>My Artikel2</name>
            <money>1234.00</money>
        </item>
    </mx:XMLList>
 
    <mx:DataGrid id="dGrid" dataProvider="{xmlDP}">
        <mx:columns>
            <mx:DataGridColumn dataField="id" />
            <mx:DataGridColumn dataField="name" />
            <mx:DataGridColumn dataField="money" labelFunction="money_labelFunc" />
        </mx:columns>
    </mx:DataGrid>
 
    <mx:Label id="sdkVer" selectable="true" initialize="sdkVer.text = mx_internal::VERSION;" />
 
</mx:Application>

Furthermore, if you wanted to format the money column with thousand separators and/or dollar signs, you could use a NumberFormatter or CurrencyFormatter, as seen in the following example:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
 
    <mx:Script>
        <![CDATA[
            import mx.controls.dataGridClasses.DataGridColumn;
 
            private function money_labelFunc(item:Object, col:DataGridColumn):String {
                // return numFormatter.format(item.money.text());
                return currFormatter.format(item.money.text());
            }
        ]]>
    </mx:Script>
 
    <mx:NumberFormatter id="numFormatter" precision="2" useThousandsSeparator="true" />
    <mx:CurrencyFormatter id="currFormatter" precision="2" useThousandsSeparator="true" />
 
    <mx:XMLList id="xmlDP" xmlns="">
        <item>
            <id>123456</id>
            <name>My Artikel</name>
            <money>10.00</money>
        </item>
        <item>
            <id>123457</id>
            <name>My Artikel2</name>
            <money>1234.00</money>
        </item>
    </mx:XMLList>
 
    <mx:DataGrid id="dGrid" dataProvider="{xmlDP}">
        <mx:columns>
            <mx:DataGridColumn dataField="id" />
            <mx:DataGridColumn dataField="name" />
            <mx:DataGridColumn dataField="money" labelFunction="money_labelFunc" />
        </mx:columns>
    </mx:DataGrid>
 
    <mx:Label id="sdkVer" selectable="true" initialize="sdkVer.text = mx_internal::VERSION;" />
 
</mx:Application>

Hope that helps,
Peter

Reply

23 Atul Yadav December 19, 2009 at 4:29 am

Hi…
how we pass data from child popup to parent application.
Thnax

Reply

24 Atul Yadav December 19, 2009 at 4:32 am

Hi..
To Khow more about Flex go to below link……..
techy.limewebs.com

Reply

25 Anonymous January 12, 2010 at 10:41 pm

i want to create array of objects for data grid control n flex 3.. can u help me..

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: