O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required