home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeJava and XML, 2nd EditionSearch this book

4.5. Gotcha!

As you get into the more advanced features of SAX, you certainly don't reduce the number of problems you can get yourself into. However, these problems often become more subtle, which makes for some tricky bugs to track down. I'll point out a few of these common problems.

4.5.3. Parsing on the Reader Instead of the Filter

I've talked about pipelines in SAX in this chapter, and hopefully you got an idea of how useful they could be. However, there's an error I see among filter beginners time and time again, and it's a frustrating one to deal with. The problem is setting up the pipeline chain incorrectly: this occurs when each filter does not set the preceding filter as its parent, ending in an XMLReader instance. Check out this code fragment:

    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.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.