19.4. Adding Text Nodes to an XML Object
Problem
You want to add text nodes
to
an XML
object.
Solution
Use the createTextNode( )
and appendChild( )
methods.
Discussion
The createTextNode( )
method is very similar to
the createElement( )
method discussed in Recipe 19.3, except that it creates a new
text node instead of an XML element. As with the
createElement( )
method, the
createTextNode( )
method does not insert the
node into the XML object hierarchy but returns a reference to the
newly created node. You are responsible for inserting the text node
into the XML object using the appendChild( )
or
insertBefore( )
method.
// Create an XML object. my_xml = new XML( ); // Create an element to which to add the text node. myElement = my_xml.createElement("myFirstElement"); // Create the next node with the value "this is some text". myTextNode = my_xml.createTextNode("this is some text"); // Add the text node to the element. myElement.appendChild(myTextNode); // Add the element to the XML object my_xml.appendChild(myElement); // Displays: <myFirstElement>this is some text</myFirstElement> trace(my_xml);
Generally, text nodes are not of much use in isolation. Remember, XML
data is structured. That means that your text nodes should always be
nested in XML elements such as the
<myFirstElement>
node in the preceding
example. Therefore, we first create the element using the
createElement( )
method (see Recipe 19.3). We then create the text node and assign it a value of “this is some text”—both ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.