O'Reilly logo

Actionscript Cookbook by Joey Lott

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

19.3. Adding Elements to an XML Object

Problem

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

Solution

Use the createElement( ) method to create the element, and then use the appendChild( ) or insertBefore( ) method to add the element to the XML tree.

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

You can create XML elements using the createElement( ) method of any XML object. You should specify the element name as a string parameter passed to the createElement( ) method. The method returns a reference to the new element (an XMLnode object).

my_xml = new XML(  );

// Create a new element, <myFirstElement />.
myElement = my_xml.createElement("myFirstElement");

Although the createElement( ) method creates the new element, it doesn’t insert it into the XML tree hierarchy. Instead, you have to instruct Flash where to insert the new element using either the appendChild( ) or insertBefore( ) method. The appendChild( ) method adds the element to the end of the children elements of the XML object (or XMLNode object) from which the method is called:

// Adds the myElement element to the my_xml object.
my_xml.appendChild(myElement);

trace(my_xml);   // Displays: <myFirstElement />

// Create another element, <myFirstNestedElement />.
myNestedElement0 = my_xml.createElement("myFirstNestedElement");

// Add the new element as a child of 

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