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“.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

33 Responses to Displaying XML data in a DataGrid

  1. neox2 says:

    Hi, how can i refresh data?

  2. 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;

  3. peterd says:

    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

  4. Aaron S. says:

    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.

  5. peterd says:

    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"&gt;
        <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

  6. Derek Basch says:

    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&gt;

  7. cool says:

    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…

  8. Peter deHaan says:

    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

  9. 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.

  10. Anonymous says:

    @ 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

  11. Flex developer says:

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

  12. Flex developer says:

    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?

  13. Prashant says:

    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……?

  14. Peter deHaan says:

    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

  15. pavithra says:

    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.

  16. pavithra says:

    sending the xml file again:

    Tool1
    10.77.7.174
    Grant Control
    Steeve

    Mac
    Katie

  17. Kerstin says:

    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.

  18. Kerstin says:

    part of the XML:

    123456
    My Artikel
    10.00

  19. Kerstin says:

    OK!
    < money > 10.00< /money >

    • Peter deHaan says:

      @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

  20. Atul Yadav says:

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

  21. Atul Yadav says:

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

  22. Anonymous says:

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

  23. mutiu says:

    Hi… Great example… I would like to do the same thing loading a xml from another domain…

    I have tried with a crossdomain.xml file but I still cannot make it work.

    Any ideas?

    than you

  24. RandiR says:

    Hi. Thanks for the tut. Can you please show more examples of passing data to/from flex ? I have several scripts in biterscripting that I use to grab and parse web documents. I want to pass the parsed elements to flex. Thanks.

  25. Pradp says:

    Thankuuuuuuuuuuuuuuuuuu for a simple code unlike others :)…i have subscribed to you now

  26. DPH says:

    Thank you, thank you, thank you!

  27. Boti says:

    hy there,
    I’m new in using flex, I hope someone could help me. It is possible to add data to an xml file by flex? I mean I have a flex interface and a datagrid displays the data which is stored in an xml file, but I want to add , delete and refresh those data with the interface. I thought that xml file can work for me as a database. How I make it?

  28. Anonymous says:

    Thanks… very nice example

  29. Artemis says:

    hi,

    I am getting data from MySQL database in a Java class which returns ResultSet Object. So i am displaying in the grid.

    here is my code.

    What i want to do is , i want to get only one row of that column. Say fullName column has 30 rows. i want the first row to be displayed in the gird. Is this possible. Help will be appreciated.

    thanks,
    Artemis

  30. Do you have anymore info on this???
    Thanks