19.7. Reading Elements in an XML Tree
Problem
You want to extract the child
elements
of
an XML
or XMLnode
object.
Solution
Use the firstChild
, lastChild
,
nextSibling
, and
previousSibling
properties to read the elements
one at a time. Alternatively, use the childNodes
property to extract all the child elements as an array.
Discussion
You’ll often want to “walk” (traverse) an XML tree to extract or examine one or more elements. This is convenient for searching for a given element or processing elements in which you know (or don’t care about) their precise order.
All the child elements of an XML
or
XMLnode
object fall into one of three possible
categories: the first child, the last child, or some other sibling.
Working from this premise, you can extract the child elements of a
node using the firstChild
,
lastChild
, nextSibling
, and
previousSibling
properties. The
firstChild
and lastChild
properties return the first and last child elements of an
XML
or XMLnode
object,
respectively. Assuming that there are no whitespace nodes in an
XML
object, the root element is returned by the
firstChild
property of that object.
my_xml = new XML("<sections><a /><b /><c /><d /></sections>"); // Extract the root element (<sections>
). rootElement = my_xml.firstChild; // Extract the first child element of the root element (<a>
). aElement = rootElement.firstChild; // Extract the last child element of the root element (<d>
). dElement = rootElement.lastChild;
You can access a child element’s sibling nodes using ...
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.