e4x is so powerful, that when I'm working with XML data I'm like Nike: I just do it. It makes everything so easy.
But today I scratched my head for a while on how to achieve a simple task. A BarChart was not rendering my data in descending order. It wasn't the chart's fault, it just rendered the data in the order that the data was being supplied (first item at the bottom). Rather than ask the back end guys to change the order of the XML, I thought I would do a simple reverse() on the data.
Alas, none of the XML, XMLList, or XMLListCollection classes have a reverse() method. That would be a nice enhancement, in my opinion... to be able to reverse the order of an element's child tags.
Here's what I did to get the job done. It's short and sweet, but it took me a few go-rounds to come up w/the solution, so I am documenting it here in case I need it again:
private function reverseChildren( x:XMLList ):XML
{
var root:XML = <root></root>;
var children:XMLList = x.children();
for (var i:int = children.length() - 1; i >= 0; i--)
{
root.appendChild( children[i] );
}
return root;
}
This snippet throws away the name of the orginal root tag, but that never seems to matter anyway!
2 comments: