E4X delete… not so obvious… but easy

I’ve just been trying to delete a node and all its descendants from an XML object selected on the value of an attribute. Having read the “ECMAScript for XML (E4X) Specification” (PDF) as linked to from the Flex documentation I expected to be able to write the following…

delete theXMLObject..*.(@id=="theIDtoDelete");

however the above code will generate the following Flash Player runtime error…

TypeError: Error #1119: Delete operator is not supported with operand of type XMLList

The solution is simple if not obvious. The above code should be rewritten to ensure a single node is returned rather than a list…

delete theXMLObject..*.(@id=="theIDtoDelete")[0];

Distilled from this actionscript.org thread.

9 thoughts on “E4X delete… not so obvious… but easy

  1. THANK YOU!!!
    Deleting nodes by index was starting to drive me craaazzyy so thanks alot (=

  2. not so good, i.e you have next xml:
    var xml : XML =

    function deleteNodesWithAttribute(child : XMLList, attr : String, exist : Boolean = true) : void {
        var list : XMLList;
        if(exist) list = child.(attribute(attr).length());
        else list = child.(attribute(attr).length()==0);
        var index : uint = list.length();
        while(index--) delete list[0];

    deleteNodesWithAttribute(xml.items, “country”);
    In result: it’ll delete all with attribute “country”.

  3. @dimpiax, thanks for taking an interest, and yeah, sorry that the comment system is not letting xml code through, so I’m not 100% sure what you are saying. Your comment did prompt me to take another look at this though and come up with the following which i think is a more compact alternative to your function.

    In my original line, the use of @ is quite intolerant if presented a node without the named attribute. The ‘attribute’ keyword is far more tolerant. so…

    To delete any/all nodes from theXMLObject which match the expression (in this case nodes with attribute ‘test’ of value ‘marker’) :

    var xlist:XMLList = theXMLObject..*.(attribute("test")=="marker");
    for( var i:int = xlist.length(); i > 0 ; i-- ) delete xlist[ 0 ];

    Since the xlist:XMLList references the original theXMLObject instance, we are actually deleting nodes from theXMLObject via xlist.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.