Java Reference
In-Depth Information
We can include code to process any given node type following the corresponding case label.
There is also an alternative to using
getChildNodes()
for working through the children of a node.
Calling the
getFirstChild()
method for a
Node
object returns a reference to its first child node,
and the
getNextSibling()
method returns the next sibling node - the next node on the same level
in other words. Both of these methods return
null
if the child requested does not exist. You can use
these in combination to iterate through all the child nodes of a given node. We can illustrate how this
works by writing a new version of our
listNodes()
method:
static void listNodes(Node node, String indent) {
String nodeName = node.getNodeName();
System.out.println(indent+nodeName+" Node, type is "
+node.getClass().getName()+":");
System.out.println(indent+" "+node);
Node childNode = node.getFirstChild(); // Get first child
while(childNode != null) { // While we have a child...
listNodes(childNode, indent+" "); // ...list it, then...
childNode = childNode.getNextSibling(); // ...get next child
}
}
As long as
childNode
is not
null
the
while
loop will continue to execute. Within the loop we call
listNodes()
for the current child then store a reference to the next sibling node in
childNode
.
Eventually
getNextSibling()
will return
null
when there are no more child nodes and the loop
will end. You can plug this code back into the example if you want to see it in action.
Accessing Attributes
You will usually want to access the attributes for an element, but only if it has some. You can test
whether an element has attributes by calling its
hasAttributes()
method. This will return
true
if
the element has attributes and
false
otherwise, so you might use it like this:
if(node instanceof Element && node.has Attributes()) {
// Process the element with its attributes
} else {
// Process the element without attributes
}
The
getAttributes()
method for an element returns a
NamedNodeMap
reference that contains the
attributes, the
NamedNodeMap
interface being defined in the
org.w3c.dom
package. In general, a
NamedNodeMap
object is a collection of
Node
references that can be accessed by name, or serially by
iterating through the collection. Since the nodes are attributes in this instance, the nodes will actually be
of type
Attr
.
The
NamedNodeMap
interface declares the following methods for retrieving nodes from the collection: