26
Jul
07

Displaying XML data in a DataGrid

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


15 Responses to “Displaying XML data in a DataGrid”


  1. 1 neox2 Jan 15th, 2008 at 11:42 am

    Hi, how can i refresh data?

  2. 2 Business Minded May 25th, 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;

  3. 3 peterd May 25th, 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

  4. 4 Aaron S. Oct 16th, 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.

  5. 5 peterd Oct 17th, 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

  6. 6 Derek Basch Jan 21st, 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>

  7. 7 cool Feb 16th, 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…

  8. 8 Peter deHaan Feb 17th, 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

  9. 9 Bala Mar 25th, 2009 at 9:59 am
  10. 10 Flex Freelancer Mar 25th, 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.

  11. 11 Anonymous Mar 31st, 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

  12. 12 Flex developer Apr 1st, 2009 at 12:17 am

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

  13. 13 Flex developer Apr 1st, 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?

  14. 14 Prashant Jun 24th, 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……?

  15. 15 Peter deHaan Jun 24th, 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

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




July 2007
M T W T F S S
    Aug »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Badge Farm

  • Powered by Redoable 1.2
  • Cornify
  • Feeds burnt by Feedburner
  • Feed