Adding and Removing Children from a Flex XMLList

I seem to always forget how this is done and for whatever reason there’s a lot of posts floating around with confusing information.  The XMLList doesn’t have any methods for adding and removing items, or even obtaining items at a specific index.  Adding and removing children from an XMLList in Flex is actually simple, though. The XMLList can be treated as if it were an Array.

// create an XML object with one child.
var parentXml:XML = ;

// parentXml.child is an XMLList.  add two new elements
parentXml.child[parentXml.child.length()] = ;
parentXml.child[parentXml.child.length()] = ;

// remove the 2nd item
delete parentXml.child[1];

Put this code inside a function and step through it in the debugger to see what’s happening.

One thing to note is that if you are binding controls to “parentXml”, the UI doens’t necessarily receive update events when the child nodes are manipulated.  In this case you may have to dispatch an event to force the UI to re-call the getter for parentXml.  Although, that is a subject for another post…

Tags: ,

2 Responses to “Adding and Removing Children from a Flex XMLList”

  1. Brian April 22, 2010 at 7:23 pm #

    Thanks a lot, this was really helpful.

  2. banch May 24, 2011 at 5:30 am #

    谢谢,很有用。

    (google translation) thank you. very useful.

Leave a Reply

Please leave these two fields as-is: