Java Reference
In-Depth Information
static void listNodes(Node node, String indent) {
// List the current node
String nodeName = node.getNodeName();
System.out.println(indent + " Node: " + nodeName);
short type =node.getNodeType();
System.out.println(indent+" Node Type: " + nodeType(type));
if(type == TEXT_NODE){
System.out.println(indent + " Content is: " + ((Text)node).getWholeText());
}
// Now list the child nodes
NodeList list = node.getChildNodes(); // Get the list of child nodes
if(list.getLength() > 0) { // As long as there are some...
//...list them & their children...
// ...by calling listNodes() for each
System.out.println(indent + " Child Nodes of " + nodeName + " are:");
for(int i = 0 ; i < list.getLength() ; ++i) {
listNodes(list.item(i),indent + " ");
}
}
}
Directory "TryDOM 3 with node content"
Here you store the integer that identifies the node type in a variable,
type
, that you test to see if it is a text
node. If it is, you get the contents by calling the
getWholeText()
method for the node. You have to cast the
node
reference to type
Text
; otherwise, you would not be able to call the
getWholeText()
method because
it is declared in the
Text
interface, which is a subinterface of
Node
. If you run the example again with this
further addition, you get the contents of the nodes displayed, too.
Even though you have set the parser feature to ignore ignorable whitespace, you could still get
#text
elements that contained just whitespace. The
Text
interface declares the
isElementContentWhitespace()
method that you can use to check for this — when you don't want to display an empty line, for example.
Accessing Attributes
You usually want to access the attributes for an element, but only if it has some. You can test whether an ele-
ment has attributes by calling its
hasAttributes()
method. This returns
true
if the element has attributes
and
false
otherwise, so you might use it like this:
short type = node.getNodeType();
if(type == ELEMENT_NODE && node.hasAttributes()) {
// Process the element with its attributes
} else {
// Process the element without attributes
}
The
getAttributes()
method 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.
Because the nodes are attributes in this instance, the nodes are actually of type
Attr
. In fact, you can call