Sorting and filtering data in an XMLListCollection
The following code is a brief example of sorting a Flex XMLListCollection using the Sort and SortField classes, and the XMLListCollection.sort property. We also look at filtering the XMLCollection using a custom filter function.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/22/sorting-and-filtering-data-in-an-xmllistcollection/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.collections.SortField;
import mx.collections.Sort;
import mx.controls.*;
private function init():void {
describeTypeXML = describeType(DataGrid);
factoryMethodsXLC.source = describeTypeXML.factory.method;
}
private function sortXLC():void {
var nameSort:Sort = new Sort();
nameSort.fields = [new SortField('@name', true)];
factoryMethodsXLC.sort = nameSort;
factoryMethodsXLC.refresh();
}
private function filterXLC():void {
if (filterCh.selected) {
factoryMethodsXLC.filterFunction = declaredBy_filterFunc;
factoryMethodsXLC.refresh();
} else {
factoryMethodsXLC.filterFunction = null;
factoryMethodsXLC.refresh();
}
}
private function declaredBy_filterFunc(item:XML):Boolean {
return item.@declaredBy == describeTypeXML.@name;
}
]]>
</mx:Script>
<mx:XML id="describeTypeXML" />
<mx:XMLListCollection id="factoryMethodsXLC" />
<mx:VBox>
<mx:DataGrid id="factoryMethodsGrid"
dataProvider="{factoryMethodsXLC}"
width="400"
rowCount="7">
<mx:columns>
<mx:DataGridColumn dataField="@name" />
<mx:DataGridColumn dataField="@returnType" />
<mx:DataGridColumn dataField="@declaredBy" />
</mx:columns>
</mx:DataGrid>
<mx:HBox width="100%">
<mx:Button id="sortBtn"
label="Sort ({factoryMethodsGrid.dataProvider.length} items)"
click="sortXLC()" />
<mx:Spacer width="100%" />
<mx:CheckBox id="filterCh"
label="{describeTypeXML.@name} only"
click="filterXLC()" />
</mx:HBox>
</mx:VBox>
</mx:Application>
View source is enabled in the following example.
Apparently this post has been sitting quietly in my drafts folder for so long I can’t even remember writing it, but hopefully it helps somebody out there.
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.
7 Responses to Sorting and filtering data in an XMLListCollection
-
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


Helped. Thanks.
What about a XML that looks like this:
<test name="groupname"> <test2 name="old">bla1data</test2> <test3 name="new">bla2data</test3> </test>What would the sortfunction look like?
private function sortXLC():void { var nameSort:Sort = new Sort(); nameSort.fields = [new SortField("test.test2", true)]; // This wont work... factoryMethodsXLC.sort = nameSort; factoryMethodsXLC.refresh(); }-Sjoerd
Sjoerd,
Is that the entire XML that you want to sort, or is there more?
Peter
I have been trying for days to get the XMLListCollection to filter and sort.
I am receiving this document from a web service in e4x and initialize my xmllistcollection as follows:
My xml looks like:
Where member 3 is a child of member 2 and member 2 is a child of member 1. I have tried to apply the filter and the sort and nothing happens. Here are my methods:
protected function sortItems():void { var treeSort:Sort = new Sort(); treeSort.fields = [new SortField("@id", true)]; dataSource_Tree.sort = treeSort; dataSource_Tree.refresh(); } protected function filterByColor():void { dataSource_Tree.filterFunction = colorFilter; //dataSource_Tree is XMLListCollection dataSource_LOSTree.refresh(); } protected function colorFilter(item:Object):Boolean // User selects a color by textbox { return item.@color == 'blue'; }I have traced several times and each time nothing happens to the xml. no filter, no sort… nothing. According to the Flex documentation, filterfunctions are supposed to traverse the entire xml document node by node, but when i trace the passed in item on the colorFilter I get the entire xml document. And the colorFilter method only gets called once (with the full xml) instead of item by item.
Is there a different way I need to filter a tree with nested nodes?
hello Peter :)
about sorting tree we can use @name for Sjoerd case?
northwebs.net/Sjoerd,
Does this answer your question at all? “Creating a custom sort on a DataGrid control in Flex”
Peter
Another great example. Many thanks!