Java Reference
In-Depth Information
Node Type: Text
Node: #text
Node Type: Text
How It Works
Because you have set the parser configuration in the factory object to include validating the XML, you
have to provide an
org.xml.sax.ErrorHandler
object for the parser. The
TryDOM
class implements the
warning()
,
error()
, and
fatalError()
methods declared by the
ErrorHandler
interface, so an in-
stance of this class takes care of it.
You call the
getDoctype()
method for the
Document
object to obtain the node corresponding to the
DOCTYPE
declaration:
DocumentType doctype = xmlDoc.getDoctype(); // Get the
DOCTYPE node
if(doctype == null) { // If it's not
null...
System.out.println("DOCTYPE is null");
} else { // ...output it
System.out.println("DOCTYPE node:\n" +
doctype.getInternalSubset());
}
You can see from the output that you get the complete text of the DTD from the document.
After outputting a header line showing where the document body starts, you output the contents, starting
with the root element. The
listNodes()
method does all the work. You pass a reference to the root ele-
ment that you obtain from the
Document
object with the following statement:
listNodes(xmlDoc.getDocumentElement(), " "); // Root element
& children
The first argument to
listNodes()
is the node to be listed, and the second argument is the current indent
for output. On each recursive call of the method, you append a couple of spaces. This results in each
nested level of nodes being indented in the output by two spaces relative to the parent node output.
The first step in the
listNodes()
method is to get the name of the current node by calling its
getNodeName()
method:
String nodeName = node.getNodeName(); // Get name of
this node
The next statement outputs the node itself:
System.out.println(indent + " " + nodeName);
You then output the type of the current node with the following statement:
System.out.println(indent + " Node Type: " +
nodeType(node.getNodeType()));