19.9. Reading Text Nodes and Their Values
Problem
You want to extract the value from a text node.
Solution
Extract the text node
from
its parent using the firstChild
property. Then get
the text node’s value using the
nodeValue
property.
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. ...
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.