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:
<?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“.
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.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
33 Responses to Displaying XML data in a DataGrid
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


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..
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
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.
Thankuuuuuuuuuuuuuuuuuu for a simple code unlike others :)…i have subscribed to you now
Thank you, thank you, thank you!
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?
Thanks… very nice example
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
Do you have anymore info on this???
Thanks