Java Reference
In-Depth Information
TEXT_NODE
COMMENT_NODE
NOTATION_NODE
ELEMENT_NODE
ATTRIBUTE_NODE
PROCESSING_INSTRUCTION_NODE
The advantage of using the getNodeType() method is that you can test for the node type using a switch
statement with the constants as case values. This makes it easy to farm out processing for nodes of various
types to separate methods.
A simple loop like the one in the previous code fragment is not a very practical approach to navigating
a document. In general, you have no idea of the level to which elements are nested in the document, and
this loop examines only one level. You need an approach that allows any level of nesting. This is a job for
recursion. Let's put together a working example to illustrate how you can do this.
TRY IT OUT: Listing a Document
You can extend the previous example to list the nodes in a document. You add a static method to the
TryDOM class to list child elements recursively. You also add a helper method that identifies what each
node is. The program outputs 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.*;
import java.nio.file.*;
import static org.w3c.dom.Node.*;
// For node
type constants
public class TryDOM implements ErrorHandler {
public static void main(String args[]) {
if(args.length == 0) {
System.out.println("No file to process." + "Usage is:\njava
TryDOM \"filename\"");
System.exit(1);
}
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
// Set
namespace aware
builderFactory.setValidating(true);
// & validating
parser
DocumentBuilder builder = null;
try {
Search WWH ::




Custom Search