Deleting nodes from an XML object in Flex

The following example shows how you can delete nodes from an XML object using the delete operator.

Full code after the jump.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/07/23/deleting-nodes-from-an-xml-object-in-flex/ -->
<mx:Application name="XML_delete_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">
 
    <mx:Script>
        <![CDATA[
            protected function btn1_clickHandler(evt:MouseEvent):void {
                delete someXML.nodeToDelete;
                txtArea.text = someXML.toXMLString();
            }
 
            protected function btn2_clickHandler(evt:MouseEvent):void {
                delete someXML.child.(@label == 'two')[0];
                txtArea.text = someXML.toXMLString();
            }
        ]]>
    </mx:Script>
 
    <mx:XML id="someXML">
        <root>
            <child label="one" />
            <child label="two" />
            <child label="three" />
            <nodeToDelete label="four" />
            <child label="five" />
            <nodeToDelete label="six">
                <child label="seven" />
                <child label="eight" />
            </nodeToDelete>
            <child label="nine" />
        </root>
    </mx:XML>
 
    <mx:ApplicationControlBar dock="true">
        <mx:Button id="btn1"
                label="delete &lt;nodeToDelete&gt; nodes"
                click="btn1_clickHandler(event);" />
        <mx:Button id="btn2"
                label="delete &lt;child label='two'&gt; node"
                click="btn2_clickHandler(event);" />
    </mx:ApplicationControlBar>
 
    <mx:TextArea id="txtArea"
            text="{someXML.toXMLString()}"
            width="300" height="200" />
 
</mx:Application>

9 thoughts on “Deleting nodes from an XML object in Flex

  1. Thank you very much for the heads-up. I just checked the Actionscript documentation and it was hidden in plain sight after so many months looking for it.

  2. Thanks for the ‘delete node’ snippet, it really worked for me.

    With kind regards,
    Satheesh C.

    1. Is there a possibility to add or remove nodes from a local xml file that is loaded with a httpService and stored in an ArrayCollection?

      kind regards
      Joris VDK

    2. Is there a possibility to add or remove nodes from a local xml file that is loaded with a httpService and stored in an ArrayCollection?

      kind regards
      Joris

Comments are closed.