Recipe 19.3 Adding Elements to an XML Object

19.3.1 Problem

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

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

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

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

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

// Add the new element as a child of myElement.

// Displays: <myFirstElement><myFirstNestedElement /></myFirstElement>

If you want to insert an element before another child element (instead of simply appending it to the end of the list of child nodes), use the insertBefore( ) method. This method works just like the appendChild( ) method except that you also need to supply a reference to the element before which the new element is inserted.

// Create and append a third nested element (before adding the second).
myNestedElement2 = my_xml.createElement("myThirdNestedElement");

// Displays: <myFirstElement><myFirstNestedElement />
//           <myThirdNestedElement /></myFirstElement>

// Create the second element and insert it before the third element.
myNestedElement1 = my_xml.createElement("mySecondNestedElement");
myElement.insertBefore(myNestedElement1, myNestedElement2);

// Displays: <myFirstElement><myFirstNestedElement />
//           <mySecondNestedElement /><myThirdNestedElement /></myFirstElement>

19.3.4 See Also

Recipe 19.4

    Part I: Local Recipes
    Part II: Remote Recipes