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:
<?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>
<?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 }
Hi, how can i refresh data?
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;
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
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.
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
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>
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…
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
Hey Any one help me in following case
t1value
t2vlasue
l1vall2Val
2t1value
2t2vlasue
l1vall2Val
i have to show 2 rows for each l1 and l2 need to show as seperate rows in dataGRID
expected result:
t1value t2value l1val
t1value t2value l2val
2t1value t2value l1val
2t1value t2value l2val
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.
@ 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
@rahul
You can access the files in your pc in this way..file:///C:\XML\XYZ.xml
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?
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……?
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
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.
sending the xml file again:
Tool1
10.77.7.174
Grant Control
Steeve
Mac
Katie
pavithra,
You need to change your < chars to < and your > to > to get the raw XML/MXML code to appear on the site.
Sorry,
Peter
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.
part of the XML:
123456
My Artikel
10.00
OK!
< money > 10.00< /money >
@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):
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: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:
Hope that helps,
Peter
Hi…
how we pass data from child popup to parent application.
Thnax
Hi..
To Khow more about Flex go to below link……..
techy.limewebs.com
i want to create array of objects for data grid control n flex 3.. can u help me..