O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding Elements to an XML Object

Problem

You want to construct an XML object and add elements to it.

Solution

Use E4X syntax to create child elements and add them to an XML tree. Additionally, use the insertChildBefore() and insertChildAfter() methods for more control over how new elements are added.

Discussion

You might want to add elements to an XML object to construct an XML data structure to pass to another application. There are several ways to accomplish this, as discussed in Recipe 20.2.

Adding elements to an existing XML object is simple with E4X syntax. Use the dot operator (.) on the XML instance and add the element much the same way a generic property is added to a regular Object:

// Create an XML instance to add elements to
var example:XML = <example />;

// Create a new XML node named newElement and add it to the 
// example instance
example.newElement = <newElement />;

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

In the preceding example, an XML literal is created for an empty newElement node. This is then added to the example instance by using the dot operator and assigning a newElement property to the newElement node. In this situation, the property name and the element name do not need to be the same. However, it would be confusing if they were not. The element name overrides the property name when adding an XML node to an existing XML object.

You can also create a new element by creating a property on the XML instance and assigning it a value, as ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required