ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button O'Reilly Book Excerpts: NetBeans: The Definitive Guide

NetBeans: Working with XML, Part 3

Related Reading

NetBeans: The Definitive Guide
By Tim Boudreau, Jesse Glick, Simeon Greene, Vaughn Spurlin, Jack J. Woehr

by Tim Boudreau, Jack J. Woehr, Vaughn Spurlin, Jesse Glick, Simeon Greene

In this final installment on working with XML, excerpted from NetBeans: The Definitive Guide, learn how to generate Java classes.

Generating Java Classes

Here comes the best part (after all, we are Java programmers): generating Java source code to process XML documents. First, we'll create a SAX document handler to read through our sample XML document and extract its element and attribute values. This gives us serial read-only access, useful in applications that need to get the information in an XML document quickly with minimal memory requirements. Next, we'll create a DOM tree scanner, useful in applications that need to access the information from an XML document in random order, update it, and output a modified XML document.

Generating a SAX Document Handler

Our next example will be a basic Simple API for XML (SAX) parser that simply lists the attributes and text in our Inventory.xml XML document. First, we will use the SAX Document Handler Wizard to generate source for the Java classes that will parse Inventory.xml. We will add a few lines of code to invoke the parser and display the parsed information. Finally, we will configure the execution service parameters and run it.

To launch the Wizard, right-click the DTD file Inventory_Inventory and then select SAX Document Handler Wizard from the context menu. The wizard's frame 1 of 4 specifies the API versions to use in generating code. For our example, select JAXP 1.1, not JAXP 1.0. Select SAX 2.0, not 1.0. Check the checkbox Propogate SAX Events to Generated Handler. Frame 2 allows you to customize the handling of each element. Accept the defaults because no special handling is needed. Frame 3 allows you to specify converter methods in case the extracted data requires a format conversion. Accept the defaults because no conversion is needed. Frame 4 allows you to specify the output File Names. Accept defaults for the file names, but uncheck the checkbox Save Customized Bindings. When the wizard is finished, three Java files will be generated:

In This Series

NetBeans: Working with XML, Part 2
In part two of this three-part series excerpted from NetBeans: The Definitive Guide, go beyond editing XML in your editors, within the open source NetBeans framework.

NetBeans: Working with XML, Part 1
In part one in this series of book excerpts from NetBeans: The Definitive Guide, learn how to work with XML within the NetBeans framework by installing XML support and working with XML editors.

  • Inventory_InventoryHandler.java: abstract class that declares callback methods for handling elements in Inventory.xml

  • Inventory_InventoryHandlerImpl.java: implementation of call back methods

  • Inventory_InventoryParser.java: logic to call SAX parser methods and then call handler methods to process the parsed data

After the files have been generated, a Confirm Changes dialog will pop up recommending changes in the implementation class to implement abstract methods. Check the Perform synchronization without confirmation radio button and click Process All.

Now that we have some source to work with, we need to make a few additions. First, add a main method to the parser classType or paste Example 11-5 into Inventory_InventoryParser.java.

Example 11-5: main method for Inventory_InventoryParser

public static void main(String[ ] args) throws Exception {
   Inventory_InventoryHandler handler =
      new Inventory_InventoryHandlerImpl( );
   EntityResolver resolver = null;
   Inventory_InventoryParser parser =
      new Inventory_InventoryParser(handler, resolver);
   InputSource input = new InputSource(args[0]);

All we need now is some print logic in the handler class. We will enhance a couple of callback methods in Inventory_InventoryHandlerImpl.java to handle the parsed data. Replace the characters method in Inventory_InventoryHandlerImpl.java with Example 11-6.

Example 11-6: characters method for Inventory_InventoryHandlerImpl

public void characters(char[ ] values, int param, int param2)
       throws org.xml.sax.SAXException {
   System.out.println(" Element Data: " + new String(values, param, param2));

Replace the startElement method in Inventory_InventoryHandlerImpl.java with Example 11-7. That's all the source changes we need. Right-click the package, and select Build All from the context menu to compile the classes.

Example 11-7: startElement method for Inventory_InventoryHandlerImpl

public void startElement(String str, String str1, String str2,
       org.xml.sax.Attributes attributes) throws org.xml.sax.SAXException {
   System.out.println("Element: " + str2);
   for (int i=0; i<attributes.getLength( ); i++){
      String name = attributes.getQName(i);
      String value = attributes.getValue(i);
      System.out.println("  Attribute: " + name + " = " + value);

One more step, configuring execution parameters for the parser, and we'll be ready for a test. Open the Properties sheet for Inventory_InventoryParser.java. Click the Execution tab. Set the Arguments property to Inventory.xml. Invoke the Customizer dialog for the Executor property by clicking the value and then the ellipsis button. Click the Expert tab of the Customizer dialog to expose the Working Directory property. Set Working Directory to the directory that contains the Inventory.xml file, presumably the same as the source directory in which we've been working.

Finally, we're ready to test the completed SAX parser. Right-click Inventory_InventoryParser.java and select Execute from the context menu. If all goes well, the IDE will switch to the Running workspace, open an Output Window, and produce the results shown in Example 11-8.

Example 11-8: Output from Inventory_InventoryHandlerImpl

Element: Inventory
  Attribute: Description = Kit Inventory
Element: Kit
  Attribute: Description = The first kit
Element: Part
  Attribute: Description = Part A
  Element Data: Part A in Kit
Element: Supplier
  Attribute: Description = Our favorite supplier
Element: Part
  Attribute: Description = Part A
  Element Data: Part A in Supplier
Element: Part
  Attribute: Description = Part A
  Attribute: Size = Just right
  Attribute: Color = Purple
  Element Data: Part A alone

Pages: 1, 2, 3

Next Pagearrow