Recipe 20.4.
Adding Text Nodes to an XML Object
Problem
You want to add text nodes to an XML object.
Solution
Use E4X syntax to create text nodes and add them
to an XML tree. Use the appendChild( ), prependChild( ), insertChildAfter( ), and
insertChildBefore( )
methods for more control over how the text nodes are added.
Discussion
Creating text nodes with E4X is, you guessed it, simple. The
process is very similar to the method described in Recipe
20.3. As with elements, creating text nodes is just a matter of
using the dot operator (.) to set a property on an XML
instance to any value that can be converted to a string. Here is an
example:
// Create an XML instance to work with
var example:XML = <example/>;
// Create a text node from a string
example.firstname = "Darron";
// Create a text node from a number
example.number = 24.9;
// Create a text node from a boolean
example.boolean = true;
// Create a text node from an array
example.abc = ["a", undefined, "b", "c", null, 7, false];
/* Displays:
<example>
<firstname>Darron</firstname>
<number>24.9</number>
<boolean>true</boolean>
<abc>a,,b,c,,7,false</abc>
</example>
*/
trace( example );
This example adds both text and element nodes to
the example XML instance. The value on the righthand side
of the assignment statement is converted into a string and becomes
the text node. Then the property name is converted into an element
node with the text node as a child, and the entire element node is
appended to the XML instance.
For more control over where the text nodes are
placed inside of element nodes, use either appendChild( ),
prependChild( ), insertChildBefore( ), or
insertChildAfter( ). These methods allow you to control
precisely where the text node is inserted into the XML tree:
// Create an XML instance to work with
var example:XML = <example/>;
// Append a two element node containing a text node child
// with value 2
example.appendChild( <two>2</two> );
// Prepend a one element node containing a text node child
// with value "number 1"
example.prependChild( <one>"number 1"</one> );
// After the one element node, insert a text node with
// value 1.5
example.insertChildAfter( example.one[0], 1.5 );
// Before the two element node, insert a part element node
// containing a text node child with value 1.75
example.insertChildBefore( example.two[0], <part>1.75</part> );
/* Displays:
<example>
<one>"number 1"</one>
1.5
<part>1.75</part>
<two>2</two>
</example>
*/
trace( example );
In the preceding code example, a mixed
element was created. A mixed element is one that contains not
only a child text node or child elements, but both. The
example element is mixed because it contains not only
child elements (<one>, <part>, and
<two>) but also a nested text node (with the value
of 1.5). This is perfectly valid XML, and it demonstrates that an
element can have more children than just a single
text node.
See Also
Recipe
20.3
|