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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access