ONJava.com    
 Published on ONJava.com (http://www.onjava.com/)
 See this if you're having trouble printing code examples


O'Reilly Book Excerpts: Learning Java, 2nd Edition

XML Basics for Java Developers, Part 2

by Patrick Niemeyer and Jonathan Knudsen

In this second part in a several part series on XML for Java developers from Learning Java, 2nd Edition, learn about SAX and the SAX API.

SAX

Related Reading

Learning Java
By Patrick Niemeyer, Jonathan Knudsen

SAX is a low-level, event-style mechanism for parsing XML documents. SAX originated in Java but has been implemented in many languages.

The SAX API

To use SAX, we'll be using classes from the org.xml.sax package, available from the W3C (World Wide Web Consortium). To perform the actual parsing, we'll need the javax.xml.parsers package, which is the standard Java package for accessing XML parsers. The java.xml.parsers package is part of the Java API for XML Processing (JAXP), which allows different parser implementations to be used with Java.

To read an XML document with SAX, we first register an org.xml.sax.ContentHandler class with the parser. The ContentHandler has methods that are called in response to parts of the document. For example, the ContentHandler's startElement() method is called when an opening tag is encountered, and the endElement() method is called when the tag is closed. Attributes are provided with the startElement() call. Text content of elements is passed through a separate method called characters(). The characters() method can be invoked repeatedly to supply more text as it is read, but it often gets the whole string in one bite. The following are the method signatures of these methods of the ContentHandler class.

public void startElement{
    String namespace, String localname, String qname, Attributes atts };
public void characters{
    char[] ch, int start, int len };
public void endElement{ 
    String namespace, String localname, String qname };

The qname parameter is the qualified name of the element. This is the element name, prefixed with namespace if it has one. When working with namespaces, the namespace and localname parameters are also supplied, providing the namespace and unqualified name.

The ContentHandler interface also contains methods called in response to the start and end of the document, startDocument() and endDocument(), as well as those for handling namespace mapping, special XML instructions, and whitespace that can be ignored. We'll confine ourselves to the three methods above for our examples. As with many other Java interfaces, a simple implementation, org.xml.sax.helpers.DefaultHandler, is provided for us that allows us to override just the methods we're interested in.

JAXP

To perform the parsing, we'll need to get a parser from the javax.xml.parsers package. The process of getting a parser is abstracted through a factory pattern, allowing different parser implementations to be plugged into the Java platform. The following snippet constructs a SAXParser object and an XMLReader used to parse a file:

import javax.xml.parsers.*;

SAXParserFactory factory = SAXParserFactory.newInstance(  );
SAXParser saxParser = factory.newSAXParser(  );
XMLReader parser = saxParser.getXMLReader(  );

parser.setContentHandler( myContentHandler );
parser.parse( "myfile.xml" );

You might expect the SAXParser to have the parse method. The XMLReader intermediary was added to support changes in the SAX API between 1.0 and 2.0. Later we'll discuss some options that can be set to govern how XML parsers operate. These options are normally set through methods on the parser factory (e.g., SAXParserFactory) and not the parser itself. This is because the factory may wish to use different implementations to support different required features.

In This Series

XML Basics for Java Developers, Part 5
In this final in a series of XML basics for Java developers book excerpts from Learning Java, 2nd Edition, get an introduction to XSL/XSLT and Web services.

XML Basics for Java Developers, Part 4
In part four in a series of XML basics for Java developers book excerpts from Learning Java, 2nd Edition, learn about validating documents.

XML Basics for Java Developers, Part 3
In part three in this series of book excerpts on XML basics for Java developers from Learning Java, 2nd Edition, learn about the Document Object Model (DOM).

XML Basics for Java Developers, Part 1
This is the first in a series of book excerpts on XML for Java developers from Learning Java, 2nd Edition. This excerpt covers XML fundamentals.

SAX's strengths and weaknesses

The primary motivation for using SAX instead of the higher-level APIs that we'll discuss later is that it is lightweight and event-driven. SAX doesn't require maintaining the entire document in memory. If, for example, you need to grab the text of just a few elements from a document, or if you need to extract elements from a large stream of XML, you can do so efficiently with SAX. The event-driven nature of SAX also allows you to take actions as the beginning and end tags are parsed. This can be useful for directly manipulating your own models without first going through another representation. The primary weakness of SAX is that you are operating on a tag-by-tag level with no help from the parser to maintain context.

Building a Model Using SAX

The ContentHandler mechanism for receiving SAX events is very simple. It should be easy to see how one could use it to capture the value or attributes of a single element in a document. What may be harder to see is how one could use SAX to build a real Java object model from an XML document. The following example, SAXModelBuilder, does just that. This example is a bit unusual in that we resort to using reflection to do a job that would otherwise be a burden on the developer. Later, we'll discuss more powerful tools for automatically generating and building models for use with XML documents.

In this section, we'll start by creating some XML along with corresponding Java classes that serve as the model for this XML. We'll see later that it's possible to work with XML more dynamically, without first constructing Java classes that hold all the content, but we want to start out in the most concrete and general way possible. The final step in this example is to create the generic model builder that reads the XML and populates the model classes with their data. The idea here is that the developer is creating only XML and model classes--no custom code--to do the basic parsing.

Building the XML file

The first thing we'll need is a nice XML document to parse. Luckily, it's inventory time at the zoo! The following document, zooinventory.xml, describes two of the zoo's residents, including some vital information about their diets:

<?xml version="1.0" encoding="UTF-8"?>
<!-- file zooinventory.xml -->
<Inventory>
    <Animal class="mammal">
        <Name>Song Fang</Name>
        <Species>Giant Panda</Species>
        <Habitat>China</Habitat>
        <Food>Bamboo</Food>
        <Temperament>Friendly</Temperament>
    </Animal>
    <Animal class="mammal">
        <Name>Cocoa</Name>
        <Species>Gorilla</Species>
        <Habitat>Central Africa</Habitat>
        <FoodRecipe>
            <Name>Gorilla Chow</Name>
            <Ingredient>Fruit</Ingredient>
            <Ingredient>Shoots</Ingredient>
            <Ingredient>Leaves</Ingredient>
        </FoodRecipe>
        <Temperament>Know-it-all</Temperament>
    </Animal>
</Inventory>

The document is fairly simple. The root element, <Inventory>, contains two <Animal> elements as children. <Animal> contains several simple text elements for things like name, species, and habitat. It also contains either a simple <Food> element or a compound <FoodRecipe> element. Finally, note that the <Animal> element has one attribute (class) that describes the zoological classification of the creature.

The model

Now let's make a Java object model for our zoo inventory. This part is very mechanical--easy, but tedious to do by hand. We simply create objects for each of the complex element types in our XML, using the standard JavaBeans property design patterns ("setters" and "getters") so that our builder can automatically use them later. (We'll prove the usefulness of these patterns later when we see that these same model objects can be understood by the Java XMLEncoder tool.) For convenience, we'll have our model objects extend a base SimpleElement class that handles text content for any element.

public class SimpleElement {
    StringBuffer text = new StringBuffer();
    public void addText( String s ) { text.append( s ); }
    public String getText() { return text.toString(); }
    public void setAttributeValue( String name, String value ) {
        throw new Error( getClass()+": No attributes allowed");
    }
}
public class Inventory extends SimpleElement {
   List animals = new ArrayList(  );
   public void addAnimal( Animal animal ) { animals.add( animal ); }
   public List getAnimals(  ) { return animals; }
   public void setAnimals( List animals ) { this.animals = animals; }
}

public class Animal extends SimpleElement { 
   public final static int MAMMAL = 1;
   int animalClass;
   String name, species, habitat, food, temperament;
   FoodRecipe foodRecipe;

   public void setName( String name ) { this.name = name ; }
   public String getName(  ) { return name; }
   public void setSpecies( String species ) { this.species = species ; }
   public String getSpecies(  ) { return species; }
   public void setHabitat( String habitat ) { this.habitat = habitat ; }
   public String getHabitat(  ) { return habitat; }
   public void setFood( String food ) { this.food = food ; }
   public String getFood(  ) { return food; }
   public void setFoodRecipe( FoodRecipe recipe ) { 
      this.foodRecipe = recipe; }
   public FoodRecipe getFoodRecipe(  ) { return foodRecipe; }
   public void setTemperament( String temperament ) { 
      this.temperament = temperament ; }
   public String getTemperament(  ) { return temperament; }

   public void setAnimalClass( int animalClass ) { 
      this.animalClass = animalClass; }
   public int getAnimalClass(  ) { return animalClass; }
   public void setAttributeValue( String name, String value ) { 
      if ( name.equals("class") && value.equals("mammal") )
         setAnimalClass( MAMMAL );
      else
         throw new Error("Invalid attribute: "+name);
   }
   public String toString(  ) { return name +"("+species+")"; }
}

public class FoodRecipe extends SimpleElement {
   String name;
   List ingredients = new ArrayList(  );
   public void setName( String name ) { this.name = name ; }
   public String getName(  ) { return name; }
   public void addIngredient( String ingredient ) { 
      ingredients.add( ingredient ); }
   public void setIngredients( List ingredients ) { 
      this.ingredients = ingredients; }
   public List getIngredients(  ) { return ingredients; }
   public String toString() { return name + ": "+ ingredients.toString(  ); }
}

If you are working in the NetBeans IDE, you can use the Bean Patterns wizard for your class to help you create all those get and set methods (see the "Bean patterns in NetBeans" section in Chapter 21 for details).

SAX model builder

Now let's get down to business and write our builder tool. The SAXModelBuilder we create in this section receives SAX events from parsing an XML file and constructs classes corresponding to the names of the tags. Our model builder is simple, but it handles the most common structures: elements with text or simple element data. We handle attributes by passing them to the model class, allowing it to map them to fixed identifiers (e.g., Animal.MAMMAL). Here is the code:

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.*;
import java.lang.reflect.*;

public class SAXModelBuilder extends DefaultHandler
{
    Stack stack = new Stack(  );
    SimpleElement element;

    public void startElement(
        String namespace, String localname, String qname, Attributes atts ) 
      throws SAXException
  {
      SimpleElement element = null;
        try {
            element = (SimpleElement)Class.forName(qname).newInstance(  );
        } catch ( Exception e ) {/*No class for element*/}
        if ( element == null ) 
           element = new SimpleElement(  );
        for(int i=0; i<atts.getLength(  ); i++)
           element.setAttributeValue( atts.getQName(i), atts.getValue(i) );
        stack.push( element );
    }
   public void endElement( String namespace, String localname, String qname) 
      throws SAXException
   {
      element = (SimpleElement)stack.pop(  );
      if ( !stack.empty(  ) )
         try {
            setProperty( qname, stack.peek(  ), element );
         } catch ( Exception e ) { throw new SAXException( "Error: "+e ); }
   }
   public void characters(char[] ch, int start, int len ) {
      String text = new String( ch, start, len );
      ((SimpleElement)(stack.peek(  ))).addText( text );
   }

    void setProperty( String name, Object target, Object value ) 
      throws SAXException 
   {
      Method method = null;
      try { 
         method = target.getClass(  ).getMethod( 
            "add"+name, new Class[] { value.getClass(  ) } );
      } catch ( NoSuchMethodException e ) { }
      if ( method == null ) try { 
         method = target.getClass(  ).getMethod( 
            "set"+name, new Class[] { value.getClass(  ) } );
      } catch ( NoSuchMethodException e ) { }
      if ( method == null ) try { 
         value = ((SimpleElement)value).getText(  );
         method = target.getClass(  ).getMethod( 
            "add"+name, new Class[] { String.class } );
      } catch ( NoSuchMethodException e ) { }
      try {
         if ( method == null )
            method = target.getClass(  ).getMethod( 
               "set"+name, new Class[] { String.class } );
         method.invoke( target, new Object [] { value } );
      } catch ( Exception e ) { throw new SAXException( e.toString(  ) ); }
   }
   public SimpleElement getModel(  ) { return element; }
}

The SAXModelBuilder extends DefaultHandler to help us implement the ContentHandler interface. We use the startElement(), endElement(), and characters() methods to receive information from the document.

Because SAX events follow the structure of the XML document, we use a simple stack to keep track of which object we are currently parsing. At the start of each element, the model builder attempts to create an instance of a class with the same name and push it onto the top of the stack. Each nested opening tag creates a new object on the stack until we encounter a closing tag. Upon reaching an end of the element, we pop the current object off the stack and attempt to apply its value to its parent (the enclosing element), which is the new top of the stack. The final closing tag leaves the stack empty, but we save the last value in the result variable.

Our setProperty() method uses reflection and the standard JavaBeans naming conventions to look for the appropriate property "setter" method to apply a value to its parent object. First we check for a method named add<Property> or set<Property>, accepting an argument of the child element type (for example, the addAnimal( Animal animal ) method of our Inventory object). Failing that, we look for an "add" or "set" method accepting a String argument and use it to apply any text content of the child object. This convenience saves us from having to create trivial classes for properties containing only text.

The common base class SimpleElement helps us in two ways. First, it provides a method allowing us to pass attributes to the model class. Next, we use SimpleElement as a placeholder when no class exists for an element, allowing us to store the text of the tag.

Test drive

Finally, we can test-drive the model builder with the following class, TestModelBuilder, which calls the SAX parser, setting an instance of our SAXModelBuilder as the content handler. The test class then prints some of the information parsed from the zooinventory.xml file:

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;

public class TestModelBuilder 
{
   public static void main( String [] args ) throws Exception
   {
      SAXParserFactory factory = SAXParserFactory.newInstance(  );
      SAXParser saxParser = factory.newSAXParser(  );
      XMLReader parser = saxParser.getXMLReader(  );
      SAXModelBuilder mb = new SAXModelBuilder(  );
      parser.setContentHandler( mb );
      parser.parse( "zooinventory.xml" );

      Inventory inventory = (Inventory)mb.getModel(  );
      System.out.println("Animals = "+inventory.getAnimals(  ));
      Animal cocoa = (Animal)(inventory.getAnimals(  ).get(1));
      FoodRecipe recipe = cocoa.getFoodRecipe(  );
      System.out.println( "Recipe = "+recipe );
   }
}

The output should look like this:

Animals = [Song Fang(Giant Panda), Cocoa(Gorilla)]
Recipe = Gorilla Chow: [Fruit, Shoots, Leaves]

In the following sections we'll generate the equivalent output using different tools.

Limitations and possibilities

To make our model builder more complete, we could use more robust naming conventions for our tags and model classes (taking into account packages and mixed capitalization, etc.). But more generally, we might not want to name our model classes strictly based on tag names. And, of course, there is the problem of taking our model and going the other way, using it to generate an XML document. Furthermore, as we've said, writing the model classes is tedious and error-prone. All this is a good indication that this area is ripe for autogeneration of classes. We'll discuss tools that do that a bit later in the chapter.

XMLencoder/decoder

Java 1.4 introduced a tool for serializing JavaBeans classes to XML. The java.beans package XMLEncoder and XMLDecoder classes are analogous to java.io ObjectInputStream and ObjectOutputStream. Instead of using the native Java serialization format, they store the object state in a high-level XML format. We say that they are analogous, but the XML encoder is not a general replacement for Java object serialization. Instead, it is specialized to work with objects that follow the JavaBeans design patterns, and it can only store and recover state of the object that is expressed through a bean's public properties in this way (using getters and setters).

In memory, the XMLEncoder attempts to construct a copy of the graph of beans that you are serializing, using only public constructors and JavaBean properties. As it works, it writes out these steps as "instructions" in an XML format. Later, the XMLDecoder executes these instructions and produces the result. The primary advantage of this process is that it is highly resilient to changes in the class implementation. While standard Java object serialization can accommodate many kinds of "compatible changes" in classes, it requires some help from the developer to get it right. Because the XMLEncoder uses only public APIs and writes instructions in simple XML, it is expected that this form of serialization will be the most robust way to store the state of JavaBeans. The process is referred to as "long-term persistence" for JavaBeans.

Give it a whirl. You can use the model-builder example to create the beans and compare the output to our original XML. You can add this bit to our TestModelBuilder class, which will populate the beans for you to write:

import java.beans.XMLEncoder;

XMLEncoder xmle = new XMLEncoder( System.out );
xmle.writeObject(inventory);
xmle.close(  );

Fun!

Further thoughts

It might seem at first like this would obviate the need for our SAXModelBuilder example. Why not simply write our XML in the format that XMLDecoder understands and use it to build our model? Well, although XMLEncoder is very efficient at eliminating redundancy, you can see that its output is still very verbose (about four times as large as our original XML) and not very human-friendly. Although it's possible to write it by hand, this XML format wasn't really designed for that. Finally, although XMLEncoder can be customized for how it handles specific object types, it suffers from the same problem that our model builder does in that "binding" (the namespace of tags) is determined strictly by our Java class names. As we've said before, what is really needed is a more general tool to generate classes or to map our own classes to XML and back.

Learn DOM in the next installment.

Learning Java

Related Reading

Learning Java
By Patrick Niemeyer, Jonathan Knudsen

Return to ONJava.com.

Copyright © 2009 O'Reilly Media, Inc.