One thing, among others, that Flex doesn’t have, and is important because many of its components needs XML structures, is deleting (taking out) nodes from a XML structure. This is crucial for a tree or for a menu where you need to change it dynamically. So bellow is a recursive method that will go through the whole XML and will remove the nodes specified in an array.
In goThrough method nodes are searched by the id_data XML attribute but with some minor changes you can make it search for node name.
public var menubarXML:XMLList = <root> <menuitem label="new" id_data="top"> <menuitem label="file" id_data="file"/> <menuitem label="document" id_data="document"/> <menuitem label="folder" id_data="folder" enabled="false" /> <menuitem label="other" id_data="other"/> </menuitem> <menuitem label="edit" id_data="top"> <menuitem label="undo" id_data="undo"/> <menuitem label="redo" id_data="redo"/> <menuitem type="separator"/> <menuitem label="cut" id_data="cut"/> <menuitem label="copy" id_data="copy"/> <menuitem label="paste" id_data="paste"/> <menuitem type="separator"/> <menuitem label="delete" id_data="delete"/> <menuitem label="refresh" id_data="refresh"/> </menuitem> <menuitem label="help" id_data="top"> <menuitem label="help" id_data="help"/> <menuitem label="search" id_data="search"/> <menuitem label="about" id_data="about"/> </menuitem> <menuitem label="logoff" id_data="top"> <menuitem label="logoff" id_data="logoff"/> </menuitem> </root>; public function goThrough(xml:XMLList, removeData:Array):void { if (xml.length() > 0) { for (var i:int = 0; i < xml.children().length(); i++) { if (removeData.indexOf(xml.children()[i].@id_data.toString()) != -1) { debugText.text += xml.children()[i].@id_data + "\n"; delete xml.children()[i]; } else { if (xml.children()[i].children()) { goThrough(xml.children()[i].children(),removeData); } } } } }
The method is called like:
goThrough(menubarXML, new Array('document','delete'));
and by accessing menubarXML afterwards you’ll have the XML with the specified nodes — having “document” and “delete” in id_data attribute — removed. This is working very smoothly because Flex uses, mainly, the Singleton pattern and most complex data is accessed by memory reference and this enables us that after modifying menubarXML we will have its structure modified although this was done “locally” inside a method. The debugText is a TextArea for output and in this case the taken out nodes are displayed.
So this is it and I think will help many of you a lot. We are waiting for comments and you may improve it to suit your needs.
Tags: ActionScript, structure, xml
This post was written by Andrei Ionescu
Views: 2740



















He great stuff, here something simular but with an arraycollection.
http://labs.flexcoders.nl/2007/03/29/flex-treecontrol-search-sample/
AS3 does have a very poorly documented “delete” function that you can use to delete a node and all its children. You can see an example I posted on Kiupa.
Thank you Aaron!