Java Reference
In-Depth Information
output. You'll probably want to pipe the output of the program to a paging pro-
gram such as mor e .
Traversing a DOM Tree
The WebAppConfig class of Example 19-3 parses an XML file to a DOM tree, modi-
fies the tree, then converts the tree back into an XML file. It does this using the
class XMLDocumentWriter , which is listed in Example 19-4. The write() method of
this class recursively traverses a DOM tree node by node and outputs the equiva-
lent XML text to the specified PrintWriter stream. The code is relatively straight-
forward and helps illustrate the structure of a DOM tree. Note that
XMLDocumentWriter is just an example. Among its shortcomings: it doesn't handle
every possible type of DOM node, and it doesn't output a full <!DOCTYPE> declara-
tion.
Example 19−4: XMLDocumentWriter.java
package com.davidflanagan.examples.xml;
import org.w3c.dom.*;
// W3C DOM classes for traversing the document
import java.io.*;
/**
* Output a DOM Level 1 Document object to a java.io.PrintWriter as a simple
* XML document. This class does not handle every type of DOM node, and it
* doesn't deal with all the details of XML like DTDs, character encodings and
* preserved and ignored whitespace. However, it does output basic
* well-formed XML that can be parsed by a non-validating parser.
**/
public class XMLDocumentWriter {
PrintWriter out; // the stream to send output to
/** Initialize the output stream */
public XMLDocumentWriter(PrintWriter out) { this.out = out; }
/** Close the output stream. */
public void close() { out.close(); }
/** Output a DOM Node (such as a Document) to the output stream */
public void write(Node node) { write(node, ""); }
/**
* Output the specified DOM Node object, printing it using the specified
* indentation string
**/
public void write(Node node, String indent) {
// The output depends on the type of the node
switch(node.getNodeType()) {
case Node.DOCUMENT_NODE: { // If its a Document node
Document doc = (Document)node;
out.println(indent + "<?xml version='1.0'?>"); // Output header
Node child = doc.getFirstChild(); // Get the first node
while(child != null) { // Loop 'till no more nodes
write(child, indent); // Output node
child = child.getNextSibling(); // Get next node
}
break;
}
Search WWH ::




Custom Search