Recently I had the need to sort and XMLListCollection in Flex. This seems to be a rather straightforward task. I had a XMLList where each item had an element called 'Image'. I wanted to sort by the value of the 'Image' node in descending order.
The original code was as follows:
1 2 3 4 5 6 | var z:XMLListCollection = new XMLListCollection(xmlList); var mySort:Sort = new Sort(); mySort.fields = [new SortField("Image",false,true)]; z.sort = mySort; z.refresh(); |
This seemed to work fine for some time. Eventually, the client came back and alerted us that values were now be returned incorrectly. In fact, the set of values being returned was simply a repetition of the value of the first node of the first element. How can this be corrected? Quite simply actually. I first decided not to use the built in sorting capabilities of ActionScript. I found a function and modified the code as follows (the code I modified can be found <a href="http://www.nuff-respec.com/technology/sort-xml-by-attribute-in-actionscript-3">here</a>):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public static function sortXMLByAttribute($xml:XMLList, $element:String, $options:Object = null):XMLList{ //store in array to sort on var xmlArray:Array = new Array(); for each(var item:XML in $xml){ var object:Object = { data : item, order : item.elements($element) }; xmlArray.push(object); } //sort using the power of Array.sortOn() xmlArray.sortOn('order',$options); //create a new XMLList with sorted XML var sortedXmlList:XMLList = new XMLList(); for each(var xmlObject:Object in xmlArray ){ sortedXmlList += xmlObject.data; } return sortedXmlList.copy(); } |
The I changed my original code to the following:
1 | var z:XMLListCollection = new XMLListCollection(sortXMLByAttribute(xmlList,"Image",Array.DESCENDING)); |
And that solved the problem. So why the issue in the first place? I'm not really 100% sure at the moment, but I'm looking into it. Maybe someone else out there has some input?