Java Reference
In-Depth Information
Example 19−4: XMLDocumentWriter.java (continued)
}
default: // Hopefully, this won't happen too much!
System.err.println("Ignoring node: " + node.getClass().getName());
break;
}
}
// This method replaces reserved characters with entities.
String fixup(String s) {
StringBuffer sb = new StringBuffer();
int len = s.length();
for(int i = 0; i < len; i++) {
char c = s.charAt(i);
switch(c) {
default: sb.append(c); break;
case '<': sb.append("<"); break;
case '>': sb.append(">"); break;
case '&': sb.append("&"); break;
case '"': sb.append("""); break;
case '\'': sb.append("'"); break;
}
}
return sb.toString();
}
}
Traversing a Document with DOM Level 2
Example 19-5 is a listing of
DOMTreeWalkerTreeModel.java
, a class that demon-
strates DOM tree traversal using the DOM Level 2
TreeWalker
class.
TreeWalker
is
part of the
org.w3c.dom.traversal
package. It allows you to traverse, or walk, a
DOM tree using a simple API. More importantly, however, it lets you specify what
type of nodes you want and automatically filters out all other nodes. It even allows
you to provide a
NodeFilter
class that filters nodes based on any criteria you
want.
The
DOMTreeWalkerTreeModel
implements the
javax.swing.tree.TreeModel
inter-
face, which enables you to easily display a filtered DOM tree using a Swing
JTree
component. Figure 19-1 shows a filtered
web.xml
file being displayed in this way.
What is interesting here is not the
TreeModel
methods themselves (refer to Chapter
10,
Graphical User Interfaces
for an explanation of
TreeModel
), but how the imple-
mentations of those methods use the
TreeWalker
API to traverse the DOM tree.
The
main()
method parses the XML document named on the command line, then
creates a
TreeWalker
for the parse tree. The
TreeWalker
is configured to show all
nodes except for comments and text nodes that contain only whitespace. Next, the
main()
method creates a
DOMTreeWalkerTreeModel
object for the
TreeWalker
.
Finally, it creates a
JTree
component to display the tree described by the
DOMTree-
WalkerTreeModel
.
Note that this example uses the Xerces parser because of its support for DOM
Level 2 (which, at the time of this writing, is not supported by JAXP). Because the
example uses Xerces, you must have the
xerces.jar
file in your classpath in order