One of the cornerstones of SAX-based programming is validation. In XML terminology, validation means confirming that an XML document conforms to a DTD or XML Schema.
Certainly, the traditional type of validation has its uses. If you receive XML documents from an
untrusted source (such as over the Internet) or allow users or developers to manually edit XML documents, then it's probably a good idea to validate these documents to ensure that nothing unexpected has occurred and that your applications don't have trouble processing invalid XML. You can turn on validation in SAX through the setFeature() method, as shown in Listing 1.
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setFeature("http://xml.org/sax/features/validation",
true);
reader.parse(myInputSource);
|
The problem with this type of validation is that it is extremely process-intensive. Validating every element (and its contents), every attribute, the resolved content of entity references, and more, can take a lot of time. Every time an XML document is parsed, these penalties are assessed to your application.
A much better solution is to put some customized validation in place. In this approach, you assign business rules to your validation. For a better idea of this, consider the DTD fragment shown in Listing 2.
<!ELEMENT purchaseOrder (item+, billTo, shipTo, payment)>
<!ATTLIST purchaseOrder
id CDATA #REQUIRED
tellerID CDATA #REQUIRED
orderDate CDATA #REQUIRED
>
|
With traditional validation, when a purchaseOrder element is processed, the parser must ensure that it has at least one item child, as well as billTo, shipTo, and payment children. It also ensures that it has id, tellerID, and orderDate attributes. This sounds great on its face; these are all required, so there should be no problem in making sure that they are there. However, it's actually a rare case where all of this data would be used in the same business component. In one application component, you might need to know the ID of the teller who input the order and the date it was input; this would be common in an audit of employee transactions. In another, such as order fulfillment, you might need the element children, but none of the attributes.
In both of these cases, only a partial validation of the input XML is actually required, and only a portion of the complete set of constraints needs to be checked. If you handle this partial validation yourself, and turn off global validation on the parser, you can achieve some drastic performance improvements. For example, if you need to ensure that the id and tellerID attributes are present, you could turn off this global validation, as shown in Listing 3.
reader.setFeature("http://xml.org/sax/features/validation", false);
|
You could then implement the logic shown in Listing 4 in the SAX startElement() callback, which would handle any custom, partial validation that's needed.
public startElement(String namespaceURI, String localName,
String qName, Attributes attributes)
throws SAXException {
// Handle custom validation
if (localName.equals("purchaseOrder")) {
if (attributes.getIndex("tellerID") < 0) {
throw new SAXException("Error: purchaseOrder elements must contain " +
"a tellerID attribute.");
}
if (attributes.getIndex("orderDate") < 0) {
throw new SAXException("Error: purchaseOrder elements must contain " +
"an orderDate attribute.");
}
}
// Normal XML processing
}
|
This may seem like an overly simple concept -- in fact, it is! However, by implementing this code instead of complete validation, you will see tremendous performance improvements in your applications. You'll find that your SAX-based applications run faster and smoother than ever.
- Find out more about the SAX API at the official SAX Web site.
- Read "Using SAX InputSource effectively," a previous tip by Brett McLaughlin that explains how using an InputStream to feed XML to the SAX API is safer and more efficient than using a Reader as input (developerWorks, August 2002).
- Another tip, "Converting from SAX" shows you how to SAX to communicate with applications that need DOM and JDOM inputs (developerWorks, April 2001).
- Take a closer look at SAX with the developerWorks tutorial "Understanding SAX" by Nicholas Chase (developerWorks, September 2001).
- Find more XML resources on the developerWorks XML zone. For a complete list of XML tips to date, check out the tips summary page.
-
IBM trial software: Build your next development project with trial software available for download directly from developerWorks.
- Find out how you can become an IBM Certified Developer in XML and related technologies.
- Want us to send you useful XML tips like this every week? Sign up for the developerWorks XML Tips newsletter here.

Brett McLaughlin has been working in computers since the Logo days (remember the little triangle?). He currently specializes in building application infrastructure using Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom, Inc. Brett is one of the co-founders of the Java Apache project Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine.





