Take the sting out of SAX

Generate SAX parsers with XML Schemas

1 2 Page 2
Page 2 of 2

Listing 8. The employee handler

public void end () throws SAXException
    String firstname = params.remove ("firstname").toString();
    String lastname = params.remove ("lastname").toString();
    System.out.println (office + "\t " + firstname + "\t" + lastname + 
"\t" + telephone);

If you need to do some processing, depending on the context in which an element occurs, you can use the Path object to find the current entity's context. Path is a stack containing the path of element names from the root element to the current element. Don't directly alter this stack, as doing so causes an invalid state for the SAX parser; you should use it as read-only information.

Now you can recompile the classes and run the new program. You will see the same output as Listing 2's example, with much less work and more readable source code.

Generate a simple parser

Because a computer can discover an XML file's structure by parsing the XML Schema, a Generator class can go a long way to helping create a SAX parser's structure. In this article, you learned how to create an easy-to-use skeleton SAX parser with a SAX code generator, and also saw how to use this parser to parse XML files. The code generator saves you hours of SAX parser development time, and its structure provides you with more readable and maintainable source code.

You have also received a set of source code templates that you can modify to meet your specific needs. With these templates, you can create any SAX structure. Of course, you can also apply these templates to problems other than SAX—I'd like to hear about any new and interesting ways in which you use the code generator.

Leon Messerschmidt, a Java developer and open source advocate, is currently working at Opticode Software. He has been involved in both commercial and open source Web application framework development for many years.

Learn more about this topic

  • "Programming XML in Java," Mark Johnson (JavaWorld):

1 2 Page 2
Page 2 of 2