Yesterday I needed to rid an XML node of all child nodes using ActionScript3’s E4X API. Since I’m still completely new to AS3 (and AS in general) as well as E4X I first thought the solution for this would be close to how you do it is done in DOM by just iterating over all children and executing node.removeChild(child)
, but for some reason, doing it this way didn’t always work out for me.
for (var i:int=children.length ; i >= 0; i--){
delete children[i];
}
Don’t ask me why, it sometimes didn’t work. But there is also a shorter way to do it, anyway: After taking a closer look at the E4X API in ActionScript3, I noticed the setChildren method of the XML class. First I tried stuff like setChildren(null)
and setChildren("")
, but all of that resulted in quite strange results like
<node>null</node>
or
<node></node>
At least the 2nd one is understandable since probably "" creates a new empty text-node, but anyway … Another option is passing an empty XMLList to setChildren(), which finally produced what I wanted:
<node />
And setChildren(new XMLList())
is more beautiful than iterating over all children manually, anyway ;-)
In my opinion, the documentation in this area could be a little bit more complete, but I guess this was always a little bit of a problem with XML-related documentation: How to delete stuff is most of the time only mentioned in some obscure footnote ;-)
Do you want to give me feedback about this article in private? Please send it to comments@zerokspot.com.
Alternatively, this website also supports Webmentions. If you write a post on a blog that supports this technique, I should get notified about your link π