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.

8 Comments

  1. Jazza says:

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

  2. Jeroen Beckers says:

    Thanks! 🙂

  3. dimpiax says:

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

    [code]
    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];
    }
    [/code]

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

  4. dimpiax says:

    dude, i can write any text with tags. =/

  5. creacog says:

    @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.

  6. James says:

    Thanks!!! didn’t think that way, though the error message did in a way say so…

  7. dimpiax says:

    btw guys, if u wanna delete all attributes of xml,
    you need to use this command: delete properties.chartProperties.@*;

  8. Dmitry says:

    Thanks a lot!! It helped me

Leave a Reply