public void buildTree(DefaultTreeModel treeModel,
DefaultMutableTreeNode base, String xmlURI)
throws IOException, SAXException {
// Create instances needed for parsing
XMLReader reader =
XMLReaderFactory.createXMLReader(vendorParserClass);
XMLWriter writer =
new XMLWriter(reader, new FileWriter("snapshot.xml"));
NamespaceFilter filter =
new NamespaceFilter(reader,
"http://www.oreilly.com/javaxml2",
"http://www.oreilly.com/catalog/javaxml2");
ContentHandler jTreeContentHandler =
new JTreeContentHandler(treeModel, base, reader);
ErrorHandler jTreeErrorHandler = new JTreeErrorHandler( );
// Register content handler
reader.setContentHandler(jTreeContentHandler);
// Register error handler
reader.setErrorHandler(jTreeErrorHandler);
// Register entity resolver
reader.setEntityResolver(new SimpleEntityResolver( ));
// Parse
InputSource inputSource =
new InputSource(xmlURI);
reader.parse(inputSource);
}
See anything wrong? Parsing is occurring on the
XMLReader instance, not at the end of the pipeline
chain. In addition, the NamespaceFilter instance
sets its parent to the XMLReader, instead of the
XMLWriter instance that should precede it in the
chain. These errors are not obvious, and will throw your intended
pipeline into chaos. In this example, no filtering will occur at all,
because parsing occurs on the reader, not the filters. If you correct
that error, you still won't get output, as the writer is left
out of the pipeline through improper setting of the
NamespaceFilter's parent. Setting the parent
properly sets you up, though, and you'll finally get the
behavior you expected in the first place. Be very careful with
parentage and parsing when handling SAX pipelines.