Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

17.6 -Java Xerces SAX In-depth

In this section, we switch over to the SAX XML mindset and write more Java code to explore this new paradigm. By the end of this section, you will have nearly completed your tour of the Xerces parser's XML capabilities, and you will be ready to build complete XML applications on your own.

17.6.1 The ContentHandler Interface

The premise of Java SAX is quite simple, but people marvel at the richness of its features. SAX is the epitome of interface- or contract-based development via events. Simply implement one or more of the SAX interfaces, tell the parser you want to be notified when certain XML nodes are found, and designate an XML document. As the document is parsed, your methods are called: one call, or event, for each new XML node discovered. And Apache-Xerces makes it as simple as it sounds. The SAX paradigm has crystal-clear advantages and disadvantages you need to be aware of before you write your code. Most prominently, in SAX, the XML document's components are not stored anywhere (whereas in DOM, everything is stored—and accessible via a Document-derived object). When a new Element is reached, you are handed its name and Attributes (if you have requested this behavior of the parser). Store the data, set a flag, skip it—do whatever you want. But when a new Element is found and your method is called again, the old Element has been completely forgotten (unless your code has taken the data and copied it elsewhere, such as in a report or database).

So remember the fundamentals: Implement one or more SAX interfaces and write code for the XML components you are interested in. Take a look at the most important of the SAX interfaces: org.w3c.sax.ContentHandler. Study the methods in Table 17.15, because they are the events that occur as an XML document is parsed.

TABLE 17.15 The org.w3c.sax.ContentHandler Interface

Method

Description

void

-characters(char[] ch, int start, int length)

 

-Here is where you are notified of the content of Elements if you implement this method. Caution: Test this event well—sometimes only partial chunks are sent. And make sure you use the start and length parameters—often the character buffer contains the whole document (or a large part).

void

-endDocument()

 

-When the end of the document has been reached, you receive this event. You receive this event only once, and no other events will follow—this is a good place to do clean-up or finalization.

void

-endElement(String namespaceURI, String localName, String qualifiedName)

 

-You receive one of these notifications when the end of the Element being parsed is reached. There is one endElement call for every startElement call.

void

-endPrefixMapping(String prefix)

 

-This corresponds to the startPrefixMapping call. This event (if appropriate) happens after the Element's endElement event.

void

-ignorableWhitespace(char[] ch, int start, int length)

 

-If you want to be notified when the parser hits unnecessary whitespace (for custom behavior or error-handling), implement this method.

void

-processingInstruction(String target, String data)

 

-Every time a processing instruction (other than an XML or text declaration) is reached, you are notified. (Remember that processing instructions are commands between '<?' and '?>'.)

void

setDocumentLocator(Locator locator)

 

-Use this method to receive a handy object for locating the origin of SAX document events.

void

-skippedEntity(String name)

 

-The parser must notify you if it could not locate a particular DTD (or if the parser doesn't do validation).

void

-startDocument()

 

-You receive this notification when parsing begins. This is a good place to do initialization.

void

-startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts)

 

-This is an important method to implement. Here you are given the namespace and name and all attributes associated with the Element.

void

-startPrefixMapping(String prefix, String uri)

 

-If you want to implement custom behavior when new prefixes are discovered, implement this method. In the example case of

 

<books:BOOK xmlns:books =

 

"http://www.galtenberg.net">

 

-prefix would equal 'books' and uri would equal 'http://www.galtenberg.net'.


Remember that when you implement an interface in Java, you must provide at least a body for every single method. We will show you how to work around this in Listing 17.6, but for now, send your very own ContentHandler through the SAX parser and see what comes out.

In Listing 17.5, we are simply going to report when parse events occur, with a println statement. Observe where each of the important types is imported from. Note that the characters and ignorableWhitespace events are handled differently (because their parameters are char[]s instead of Strings). Also pay attention to the parameters passed to each method; some methods have no parameters and thus are essentially pure events.

LISTING 17.5 HelloApacheSAX Example

import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.Attributes;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class HelloApacheSAX implements ContentHandler
{
  public void characters (char[] ch, int start, int length)
  {
    System.out.print("New Characters: ");
    for (int i = 0; i < length; i++)
      System.out.print(ch[start + i]);
    System.out.print("\n");
  }
  public void endDocument ()
  {
    System.out.println("End Document");
  }
  public void endElement (String namespaceURI, String localName,
                          String qualifiedName)
  {
    System.out.println("End Element:  Name = " + localName);
  }
  public void endPrefixMapping (String prefix)
  {
    System.out.println("End Prefix Mapping:  Prefix = " 
                       + prefix);
  }
  public void ignorableWhitespace (char[] ch, int start, 
                                   int length)
  {
    System.out.print("Ignorable Whitespace: ");
    for (int i = 0; i < length; i++)
      System.out.print(ch[start + i]);
    System.out.print("\n");
  }
  public void processingInstruction (String target, String data)
  {
    System.out.println("Processing Instruction:  Target = "
        + target + ", Data = " + data);
  }
  public void setDocumentLocator (Locator l)
  {
    System.out.println("\nSet Document Locator");
  }
  public void skippedEntity (String name)
  {
    System.out.println("Skipped entity:  Name = " + name);
  }
  public void startDocument ()
  {
    System.out.println("Start Document");
  }
  public void startElement (String namespace, String localName, 
                      String qualifiedName, Attributes attribs)
  {
    System.out.println("Start Element:  Name = " + localName);
  }
  public void startPrefixMapping (String prefix, String uri)
  {
    System.out.println("Start Prefix Mapping:  Prefix = " +
        prefix + ", URI = " + uri);
  }
  public static void main (String[] args)
  {
    try
    {
      XMLReader parser;
      parser = XMLReaderFactory.createXMLReader();
      parser.setContentHandler(new HelloApacheSAX());

      parser.parse(args[0]);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}

After a new parser is created, you simply inform it that your class handles notifications with the following call. (It could have been any class as long as it implemented the ContentHandler interface.)

parser.setContentHandler(new HelloApacheSAX());

The XMLReader is the actual SAX parser. If you are wondering why we did not use the parser and factory from the javax.xml.parsers package, the short answer is that the SAXParser type does not accept a basic ContentHandler-derived object. It expects a DefaultHandler-derived object (explained in Listing 17.6). But this is still the same parser: The SAXParser object actually contains an XMLReader object. You will use the SAXParser in the next sample. Simply know that the XMLReader can accept any one (or more) of the critical SAX interfaces.

If you compile and run our faithful helloapache.xml file through your new parser, the output should look like the screen shown in Figure 17.9.

Figure 17.9 FIGURE 17.9 Output of the HelloApacheSAX Example.

We only want to display element content, so as soon as the AUTHOR element is handled, it is discarded and the parser moves right on to TITLE, and so on. Execution is extremely rapid, and very little memory is used. With SAX and Xerces, you can write a full XML application in mere minutes.

Can we make this any easier? You bet! Instead of implementing the full menu of ContentHandler methods, you can simply extend a class, DefaultHandler (in the org.xml.sax.helpers package), which already implements these methods (although they do not do anything). Now implement methods only for events that interest you. If you only care about catching processingInstructions, for example, you need implement only that single method.

org.xml.sax.helpers.DefaultHandler implements four SAX interfaces, ContentHandler, DTDHandler, EntityResolver, and ErrorHandler, described in Table 17.6 when we introduced the critical SAX packages. You have seen ContentHandler—the other three interfaces have only a couple of methods each, for performing lower-level handling (see the API documentation for details). You might be interested in examining org.xml.sax.ErrorHandler, because it can also be used in DOM parsing applications. Just add code similar to the following:

ErrorHandler handler = object that implements ErrorHandler;

DocumentBuilder builder = object that implements DocumentBuilder;

builder.setErrorHandler(handler);

For nearly all SAX applications, DefaultHandler is your base class of choice. In Listing 17.6, we use DefaultHandler in collaboration with the SAXParser class from the javax.xml.parsers package. (Remember, in the future, if you want to specify exact SAX interface-implementations, access the XMLReader within the SAX parser.)

Also, you will be catching the full complement of parser exceptions. These should look familiar, because you used them in the HelloApache2 sample in Listing 17.6.

To make this final example more challenging, there are two additional assigned tasks:

Use the address.xml document to print a report, but this time, only display names and ID information.

  • Validate the document's XML schema (found in address.xsd).

The first task should be a piece of cake. You need to write just a bit of logic for the startElement, endElement, and characters methods. (And now, because you are using DefaultHandler, you do not have to write code for methods you will not use.)

Validating the XML schema is a bit more complicated. But the ride has been pretty smooth to this point, and Xerces makes schemas a breeze, too.

Xerces introduces the notion of properties and features, which are very similar to Java and Visual Basic properties. There is a key and value for each one. Simply set the data for whichever property or feature you care about. The only difference between properties and features is that features are Boolean, like on and off switches: Turn features on or off as you choose. Features can be of any type and are useful for both setting and retrieving specific parser settings.

To set features or properties for SAX processing, access the XMLReader object and call either setFeature or setProperty, with the appropriate key and value. You will find these calls in the main function block.

LISTING 17.6 HelloApacheSAX2 Example

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import java.io.IOException;
public class HelloApacheSAX2 extends DefaultHandler
{
  // A flag which indicates we've reached the Element 
  //   we're interested in
  private boolean bName = false;
  // The three methods of the ErrorHandler interface
  public void error (SAXParseException e)
  {
    System.out.println("\n***Error*** " + e);
  }
  public void warning (SAXParseException e)
  {
    System.out.println("\n***Warning*** " + e);
  }
  public void fatalError (SAXParseException e)
  {
    System.out.println("\n***Fatal Error*** " + e);
  }
  public void startDocument ()
  {
    System.out.println("\n***Start Document***");
  }
  public void endDocument ()
  {
    System.out.println("\n***End Document***");
  }
  // There are many ways to filter out Elements –
  //   this is an elementary example
  public void startElement (String namespace, String localName,
                       String qualifiedName, Attributes attribs)
                            
  {
    if (qualifiedName == "privateCustomer" ||
        qualifiedName == "businessCustomer")
    {
      System.out.println ("\nNew " + qualifiedName + " Entry:");
      for (int i = 0; i < attribs.getLength(); i++)
      {
        System.out.println(attribs.getQName(i) + ": " +
            attribs.getValue(i));
      }
    }
    else if (qualifiedName == "name")
    {
      bName = true;
    }
  }
  // Only print characters from the 'name' elements
  public void characters (char[] ch, int start, int length)
  {
    if (bName == true)
    {
      System.out.print("Name: ");
      for (int i = 0; i < length; i++)
        System.out.print(ch[start + i]);
        System.out.print("\n");
    }
  }
  // Regardless of what Element we're on, we're done with 'name'
  public void endElement (String namespaceURI, String localName,
                          String qualifiedName)
  {
    bName = false;
  }
  public static void main (String[] args)
  {
    try
    {
      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser parser = factory.newSAXParser();
      DefaultHandler handler = new HelloApacheSAX2();
      XMLReader reader = parser.getXMLReader();
      
      // set parser features
      try
      {
        reader.setFeature
            ("http://xml.org/sax/features/validation", true);
        reader.setFeature
            ("http://apache.org/xml/features/validation/schema",
             true);
        reader.setFeature ("http://apache.org/xml/features/
validation/warn-on-undeclared-elemdef", true);
        reader.setProperty
        ("http://apache.org/xml/properties/schema/external-
noNamespaceSchemaLocation", "address.xsd");
      }
      catch (SAXException e)
      {
        System.out.println
        ("Warning: Parser does not support schema validation");
      }
     
      parser.parse(args[0], handler);
    }
    catch (FactoryConfigurationError e)
    {
      System.out.println("Factory configuration error: " + e);
    }
    catch (ParserConfigurationException e)
    {
      System.out.println("Parser configuration error: " + e);
    }
    catch (SAXException e)
    {
      System.out.println("Parsing error: " + e);
    }
    catch (IOException e)
    {
      System.out.println("I/O error: " + e);
    }
  }
}

You can see that you are using a different method to retrieve your SAX parser, but XMLReader is there too (and vital for setting features and properties).

Make sure that both address.xml and address.xsd are available in your current path as you compile and run the example. Output should look similar to the screen shown in Figure 17.10.

Figure 17.10 FIGURE 17.10 Viewing output of HelloApacheSAX2 example.

You also need a socket open to the Internet, because address.xsd references another XSD document from the book.

Did you notice that execution took longer this time? Maybe you even saw the lag between the '***StartDocument***' message and the actual parsing. XML schema validation is time-consuming. Performance should improve over time as later Xerces parsers are released, but there is always a fair amount of overhead (just as there is overhead in using Java rather than a compiled language). But you succeeded in both your tasks. You will of course want to implement a more robust method of filtering Elements, and you will not want to hard-code schema locations in your reader.setProperty calls.

There are multiple ways to specify Schema functionality and file locations (in DOM as well as SAX—the code is virtually the same). In fact, entire sections in the API documentation are devoted to the dozens of properties and features. Study these well, and remember that they are subject to updates over time, so keep up with the latest Xerces releases.

  • + Share This
  • 🔖 Save To Your Account