Java Reference
In-Depth Information
Example 19−5: DOMTreeWalkerTreeModel.java (continued)
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
/**
* This main() method demonstrates the use of this class, the use of the
* Xerces DOM parser, and the creation of a DOM Level 2 TreeWalker object.
**/
public static void main(String[] args) throws IOException, SAXException {
// Obtain an instance of a Xerces parser to build a DOM tree.
// Note that we are not using the JAXP API here, so this
// code uses Apache Xerces APIs that are not standards
DOMParser parser = new org.apache.xerces.parsers.DOMParser();
// Get a java.io.Reader for the input XML file and
// wrap the input file in a SAX input source
Reader in = new BufferedReader(new FileReader(args[0]));
InputSource input = new org.xml.sax.InputSource(in);
// Tell the Xerces parser to parse the input source
parser.parse(input);
// Ask the parser to give us our DOM Document. Once we've got the DOM
// tree, we don't have to use the Apache Xerces APIs any more; from
// here on, we use the standard DOM APIs
Document document = parser.getDocument();
// If we're using a DOM Level 2 implementation, then our Document
// object ought to implement DocumentTraversal
DocumentTraversal traversal = (DocumentTraversal)document;
// For this demonstration, we create a NodeFilter that filters out
// Text nodes containing only space; these just clutter up the tree
NodeFilter filter = new NodeFilter() {
public short acceptNode(Node n) {
if (n.getNodeType() == Node.TEXT_NODE) {
// Use trim() to strip off leading and trailing space.
// If nothing is left, then reject the node
if (((Text)n).getData().trim().length() == 0)
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
};
// This set of flags says to "show" all node types except comments
int whatToShow = NodeFilter.SHOW_ALL & ˜NodeFilter.SHOW_COMMENT;
// Create a TreeWalker using the filter and the flags
TreeWalker walker = traversal.createTreeWalker(document, whatToShow,
filter, false);
// Instantiate a TreeModel and a JTree to display it
JTree tree = new JTree(new DOMTreeWalkerTreeModel(walker));
// Create a frame and a scrollpane to display the tree, and pop them up
JFrame frame = new JFrame("DOMTreeWalkerTreeModel Demo");
frame.getContentPane().add(new JScrollPane(tree));
frame.setSize(500, 250);
Search WWH ::




Custom Search