Java Reference
In-Depth Information
A
NodeList
reference encapsulates an ordered collection of
Node
references, each of which may be
one or other of the possible node types for the current node. So with an
Element
node, any of the
Node
references in the list that is returned can be of type
Element
,
Text
,
Comment
,
CDATASection
,
EntityReference
, or
ProcessingInstruction
. Note that if there are no child nodes, the
getChildNodes()
method will return a
NodeList
reference that is empty, not
null
. You call the
getChildNodes()
method to obtain a list of child nodes for any node type that can have them.
The
NodeList
interface declares just two methods:
getLength()
Returns the number of nodes in the list as type
int
.
item(int index)
Returns a reference of type
Node
to the object at position
index
in the
list.
We can use these methods to iterate through the child elements of the root element, perhaps like this:
Node[] nodes = new Node[children.getLength()];
for(int i = 0 ; i<nodes.getLength() ; i++)
nodes[i] = children.item(i);
Of course, we will normally be interested in the specific types of nodes that are returned so we will want
to extract them as specific types or at least determine what they are before processing them. This is not
difficult. You can test the type of any node using the
instanceof
operator. Here's one way we could
extract just the child nodes that are of type
Element
:
java.util.Vector elements = new java.util.Vector();
Node node = null;
for(int i = 0 ; i<nodes.getLength() ; i++) {
node = children.item(i);
if(node instanceof Element)
elements.add(node);
}
A simple loop like this is not a very practical approach to navigating a document. In general we have no
idea of the level to which elements are nested in a document and this loop only examines one level. We
need an approach that will allow any level of nesting. This is a job for recursion. Let's put together a
working example to illustrate this.
Try It Out - Listing a Document
We can extend the previous example to list the nodes in a document. We will add a
static
method to
the
TryDOM
class to list child elements recursively. We will output details of each node followed by its
children. Here's the code:
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;
import java.io.File;