How to sort XML
Copy link to clipboard
Copied
I have an XML like this:
<node label="California">
<node label="location 1" />
<node label="location 2">
<node label="option 1" />
<node label="option 2" />
</node>
</node>
<node label="Oregon">
<node label="Portland" />
</node>
I'm using the XML as a data provider for the Astra Tree component (http://developer.yahoo.com/flash/astra-flash/tree/) I want to sort each node and each child node in alpha order and I'm trying to figure out the best way to go about it.
I've found this code which sorts XMLLists:
function sortXMLList(list:XMLList, fieldName:Object, options:Object = null):XMLList {
var i:int;
var arr:Array = new Array();
var ch:XML;
for each (ch in list) {
arr.push(ch);
}
var resultArr:Array = [];
if (fieldName == null && options == null) {
resultArr = arr.sort();
} else if (fieldName==null) {
resultArr = arr.sort(options);
} else {
resultArr = arr.sortOn(fieldName,options);
}
var result:XMLList = new XMLList();
for(i=0; i<resultArr.length; i++){;
result += XML(resultArr);
}
return result;
}
But it doesn't work directly on XML and I'm having a hard time figuring out how to go through all levels (the sample above only has three, but the final xml might have more nested levels) and sort it in alpha order.
Any ideas?
Copy link to clipboard
Copied
Never mind — sort of....
I changed how the XML object is being generated and so it is now sorted in alpha order.
But the question still hangs out there. Is there an "easy" way to sort an XML and all its children (and their children) into a specific order?
Copy link to clipboard
Copied
Check the two functions at the bottom of this post. XML can be tricky as it's so abstract:
Copy link to clipboard
Copied
Interesting. Thanks. I didn't know xml.setChildren. I think that will help a lot.

