[ Team LiB ] |
Recipe 19.3 Adding Elements to an XML Object19.3.1 ProblemYou want to construct an XML object and add elements to it. 19.3.2 SolutionUse 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 DiscussionYou 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 myElement. myElement.appendChild(myNestedElement0); // Displays: <myFirstElement><myFirstNestedElement /></myFirstElement> trace(my_xml); 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"); myElement.appendChild(myNestedElement2); // Displays: <myFirstElement><myFirstNestedElement /> // <myThirdNestedElement /></myFirstElement> trace(my_xml); // 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> trace(my_xml); 19.3.4 See Also |
[ Team LiB ] |