Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Tip: Customized validation in SAX

Speed up parsing with customized validation

Brett McLaughlin (brett@newInstance.com), Author and Editor, O'Reilly Media Inc.
Photo of Brett McLaughlin
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.

Summary:  This tip explains how to use a partial validation approach, rather than the full-blown validation that's included in parsing APIs. By validating only what is absolutely required, you can save tons of processing time.

View more content in this series

Date:  01 Aug 2002
Level:  Introductory

Comments:  

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.

Traditional validation

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.


Customized validation

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.


Resources

About the author

Photo of Brett McLaughlin

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.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


Forgot your IBM ID?


Forgot your password?
Change your password


By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)


By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML
ArticleID=12152
ArticleTitle=Tip: Customized validation in SAX
publish-date=08012002
author1-email=brett@newInstance.com
author1-email-cc=htc@us.ibm.com

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).