Recipe 19.9 Reading Text Nodes and Their Values

19.9.1 Problem

You want to extract the value from a text node.

19.9.2 Solution

Extract the text node from its parent using the firstChild property. Then get the text node's value using the nodeValue property.

19.9.3 Discussion

In Recipe 19.4 we looked at text nodes and how to create them in your XML objects. Now we want to look at how to extract the value from a text node. You can use the firstChild, lastChild, nextSibling, previousSibling, and childNodes properties discussed in Recipe 19.7 to get a reference to a text node the same way you would get a reference to any other node (such as an element). Then, once you have a reference to the text node, use the nodeValue property to retrieve that node's text value.

An example will help illustrate. Let's consider the following XML packet:

<book>   <title>ActionScript Cookbook</title> </book>

In this XML packet, the root node is <book>, which contains a child element, <title>. The <title> element, in turn, contains a nested node a text node with a value of "ActionScript Cookbook".

If we parse this XML packet into an XML object, we can get the root node by using the firstChild property. Then we can get the <title> element with the firstChild property of the root node. And finally, we can get the text node with the firstChild property of the <title> element.

my_xml = new XML("<book><title>ActionScript Cookbook</title></book>"); // Extract the root node (<book>). bookElement = my_xml.firstChild; // Extract the <title> element. titleElement = bookElement.firstChild; // Extract the text node (ActionScript Cookbook). titleTextNode = titleElement.firstChild;

Once you have extracted a text node, you can read its value using the nodeValue property:

value = titleTextNode.nodeValue; trace(value); // Displays: ActionScript Cookbook

19.9.4 See Also

Recipe 19.4

ActionScript Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2005
Pages: 425

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: