Home > Articles > Programming > Java

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020