Deleting nodes from an XML object in Flex

by Peter deHaan on July 23, 2009

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>

{ 4 comments… read them below or add one }

Tomas Sancio July 23, 2009 at 8:49 pm

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.

Reply

stoimen July 23, 2009 at 11:45 pm

Thanks for the nice post, actually it was exactly what I was searching for!

Reply

sathishkumar July 24, 2009 at 12:32 am

Thanks for this information
this is what i exactly want
thanks alot for this post

Reply

Satheesh Chakravarthi December 7, 2009 at 5:33 am

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

With kind regards,
Satheesh C.

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: