Previous Page
Next Page

Recipe 20.10. Removing Elements, Text Nodes, and Attributes

Problem

You want to remove an element node, text node, or attribute from an XML object.

Solution

Use the delete keyword.

Discussion

In previous recipes you have learned how to add element and text nodes, and attributes to XML objects. You've also learned how to read them back in and loop over them. But what if you want to delete a particular element or attribute? The secret is to use the delete keyword, followed by what you want to delete:

var example:XML = <example>
                    <fruit color="Red">Apple</fruit>
                    <vegetable color="Green">Broccoli</vegetable>
                    <dairy color="White">Milk</dairy>
                  </example>;
                  
// Remove the color attribute from the fruit element
delete example.fruit.@color;

// Remove the dairy element entirely
delete example.dairy;

// Remove the text node from the vegetable element node
delete example.vegetable.text(  )[0];

/* Displays:
<example>
  <fruit>Apple</fruit>
  <vegetable color="Green"/>
</example>
*/
trace( example );

Of particular interest in the preceding example is how the text node was deleted. Using certain methods like text( ) and elements( ) on an XML object, or, in certain situations, using E4X syntax, returns an XMLList with multiple items. The delete keyword only works in conjunction with a single item, and as such, you must use bracket notation to reference a particular item in the XMLList that you want to delete. To delete all the items in the XMLList, use a for loop and iterate over the items in reverse order:

var example:XML = <example>
                    <fruit color="red" name="Apple" />
                  </example>;

// Get an XMLList of the attributes for fruit
var attributes:XMLList = example.fruit.@*;

// Loop over the items backwards to delete every attribute. 
// By removing items from the end of the array we avoid problems 
// with the array indices changing while trying to loop over them.
for ( var i:int = attributes.length(  ) - 1; i >= 0; i-- ) {
    delete attributes[i];
}

/* Displays:
<example>
  <fruit/>
</example>
*/
trace( example );


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)