Sorting and filtering data in an XMLListCollection

by Peter deHaan on August 22, 2007

in Sort, SortField, 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.

View MXML

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

{ 7 comments… read them below or add one }

1 mare September 10, 2007 at 12:40 pm

Helped. Thanks.

Reply

2 Sjoerd September 26, 2007 at 2:10 am

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

Reply

3 peterd September 26, 2007 at 11:42 pm

Sjoerd,

Is that the entire XML that you want to sort, or is there more?

Peter

Reply

4 Shawn January 17, 2008 at 7:28 am

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?

Reply

5 northwebs.net April 9, 2008 at 9:33 am

hello Peter :)

about sorting tree we can use @name for Sjoerd case?

Reply

6 peterd April 9, 2008 at 9:14 pm

northwebs.net/Sjoerd,

Does this answer your question at all? “Creating a custom sort on a DataGrid control in Flex”

Peter

Reply

7 Geoff October 3, 2008 at 8:08 am

Another great example. Many thanks!

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: