The Java XML Validation API

Check your documents for conformance to schemas

Validation reports whether a document adheres to the rules specified by the schema. Different parsers and tools support different schema languages such as DTDs, the W3C XML Schema Language, RELAX NG, and Schematron. Java 5™ adds a uniform validation Application Programming Interface (API) that can compare documents to schemas written in these and other languages. Learn about this XML validation API.

Share:

Elliotte Rusty Harold (elharo@metalab.unc.edu), Adjunct Professor, Polytechnic University

Photo of Elliot Rusty HaroldElliotte Rusty Harold is originally from New Orleans, to which he returns periodically in search of a decent bowl of gumbo. However, he resides in the Prospect Heights neighborhood of Brooklyn with his wife Beth and cats Charm (named after the quark) and Marjorie (named after his mother-in-law). He's an adjunct professor of computer science at Polytechnic University, where he teaches Java and object-oriented programming. His Cafe au Lait Web site has become one of the most popular independent Java sites on the Internet, and his spin-off site, Cafe con Leche, has become one of the most popular XML sites. His most recent book is Java I/O, 2nd edition. He's currently working on the XOM API for processing XML, the Jaxen XPath engine, and the Jester test coverage tool.



10 February 2010 (First published 08 August 2006)

Also available in Chinese Russian Japanese Vietnamese

10 Feb 2010 - As a followup to reader comments, the author made updates to the final paragraph under Validation Only the schema is thread safe, validators and schema factories are not.

Validation is a powerful tool. It enables you to quickly check that input is roughly in the form you expect and quickly reject any document that is too far away from what your process can handle. If there's a problem with the data, it's better to find out earlier than later.

In the context of Extensible Markup Language (XML), validation normally involves writing a detailed specification for the document's contents in any of several schema languages such as the World Wide Web Consortium (W3C) XML Schema Language (XSD), RELAX NG, Document Type Definitions (DTDs), and Schematron. Sometimes validation is performed while parsing, sometimes immediately after. However, it's usually done before any further processing of the input takes place. (This description is painted with broad strokes -- there are exceptions.)

Until recently, the exact Application Programming Interface (API) by which programs requested validation varied with the schema language and parser. DTDs and XSD were normally accessed as configuration options in Simple API for XML (SAX), Document Object Model (DOM), and Java™ API for XML Processing (JAXP). RELAX NG required a custom library and API. Schematron might use the Transformations API for XML(TrAX); and still other schema languages required programmers to learn still more APIs, even though they were performing essentially the same operation.

Java 5 introduced the javax.xml.validation package to provide a schema-language-independent interface to validation services. This package is also available in Java 1.3 and later when you install JAXP 1.3 separately. Among other products, an implementation of this library is included with Xerces 2.8.

Validation

The javax.xml.validation API uses three classes to validate documents: SchemaFactory, Schema, and Validator. It also makes extensive use of the javax.xml.transform.Source interface from TrAX to represent the XML documents. In brief, a SchemaFactory reads the schema document (often an XML file) from which it creates a Schema object. The Schema object creates a Validator object. Finally, the Validator object validates an XML document represented as a Source.

Listing 1 shows a simple program to validate a URL entered on the command line against the DocBook XSD schema.

Listing 1. Validating an Extensible Hypertext Markup Language (XHTML) document
import java.io.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.SAXException;

public class DocbookXSDCheck {

    public static void main(String[] args) throws SAXException, IOException {

        // 1. Lookup a factory for the W3C XML Schema language
        SchemaFactory factory = 
            SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        
        // 2. Compile the schema. 
        // Here the schema is loaded from a java.io.File, but you could use 
        // a java.net.URL or a javax.xml.transform.Source instead.
        File schemaLocation = new File("/opt/xml/docbook/xsd/docbook.xsd");
        Schema schema = factory.newSchema(schemaLocation);
    
        // 3. Get a validator from the schema.
        Validator validator = schema.newValidator();
        
        // 4. Parse the document you want to check.
        Source source = new StreamSource(args[0]);
        
        // 5. Check the document
        try {
            validator.validate(source);
            System.out.println(args[0] + " is valid.");
        }
        catch (SAXException ex) {
            System.out.println(args[0] + " is not valid because ");
            System.out.println(ex.getMessage());
        }  
        
    }

}

Here's some typical output when checking an invalid document using the version of Xerces bundled with Java 2 Software Development Kit (JDK) 5.0:

file:///Users/elharo/CS905/Course_Notes.xml is not valid because cvc-complex-type.2.3: Element 'legalnotice' cannot have character [children], because the type's content type is element-only.

You can easily change the schema to validate against, the document to validate, and even the schema language. However, in all cases, validation follows these five steps:

  1. Load a schema factory for the language the schema is written in.
  2. Compile the schema from its source.
  3. Create a validator from the compiled schema.
  4. Create a Source object for the document you want to validate. A StreamSource is usually simplest.
  5. Validate the input source. If the document is invalid, the validate() method throws a SAXException. Otherwise, it returns quietly.

You can reuse the same validator and the same schema multiple times in series. However, only the schema is thread safe. Validators and schema factories are not. If you validate in multiple threads simultaneously, make sure each one has its own Validator and SchemaFactory objects.

Validate against a document-specified schema

Some documents specify the schema they expect to be validated against, typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes like this:

<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="http://www.example.com/document.xsd">
  ...

If you create a schema without specifying a URL, file, or source, then the Java language creates one that looks in the document being validated to find the schema it should use. For example:

SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema();

However, normally this isn't what you want. Usually the document consumer should choose the schema, not the document producer. Furthermore, this approach works only for XSD. All other schema languages require an explicitly specified schema location.


Abstract factories

SchemaFactory is an abstract factory. The abstract factory design pattern enables this one API to support many different schema languages and object models. A single implementation usually supports only a subset of the numerous languages and models. However, once you learn the API for validating DOM documents against RELAX NG schemas (for instance), you can use the same API to validate JDOM documents against W3C schemas.

For example, Listing 2 shows a program that validates DocBook documents against DocBook's RELAX NG schema. It's almost identical to Listing 1. The only things that have changed are the location of the schema and the URL that identifies the schema language.

Listing 2. Validating a DocBook document using RELAX NG
import java.io.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.SAXException;

public class DocbookRELAXNGCheck {

    public static void main(String[] args) throws SAXException, IOException {

        // 1. Specify you want a factory for RELAX NG
        SchemaFactory factory 
         = SchemaFactory.newInstance("http://relaxng.org/ns/structure/1.0");
        
        // 2. Load the specific schema you want. 
        // Here I load it from a java.io.File, but we could also use a 
        // java.net.URL or a javax.xml.transform.Source
        File schemaLocation = new File("/opt/xml/docbook/rng/docbook.rng");
        
        // 3. Compile the schema.
        Schema schema = factory.newSchema(schemaLocation);
    
        // 4. Get a validator from the schema.
        Validator validator = schema.newValidator();
        
        // 5. Parse the document you want to check.
        String input 
         = "file:///Users/elharo/Projects/workspace/CS905/build/Java_Course_Notes.xml";
        
        // 6. Check the document
        try {
            validator.validate(source);
            System.out.println(input + " is valid.");
        }
        catch (SAXException ex) {
            System.out.println(input + " is not valid because ");
            System.out.println(ex.getMessage());
        }  
        
    }

}

If you run this program with the stock Sun JDK and no extra libraries, you'll probably see something like this:

Exception in thread "main" java.lang.IllegalArgumentException: 
http://relaxng.org/ns/structure/1.0
	at javax.xml.validation.SchemaFactory.newInstance(SchemaFactory.java:186)
	at DocbookRELAXNGCheck.main(DocbookRELAXNGCheck.java:14)

This is because, out of the box, the JDK doesn't include a RELAX NG validator. When the schema language isn't recognized, SchemaFactory.newInstance() throws an IllegalArgumentException. However, if you install a RELAX NG library such as Jing and a JAXP 1.3 adapter, then it should produce the same answer the W3C schema does.

Identify the schema language

The javax.xml.constants class defines several constants to identify schema languages:

  • XMLConstants.W3C_XML_SCHEMA_NS_URI: http://www.w3.org/2001/XMLSchema
  • XMLConstants.RELAXNG_NS_URI: http://relaxng.org/ns/structure/1.0
  • XMLConstants.XML_DTD_NS_URI: http://www.w3.org/TR/REC-xml

This isn't a closed list. Implementations are free to add other URLs to this list to identify other schema languages. Typically, the URL is the namespace Uniform Resource Identifier (URI) for the schema language. For example, the URL http://www.ascc.net/xml/schematron identifies Schematron schemas.

Sun's JDK 5 only supports XSD schemas. Although DTD validation is supported, it isn't accessible through the javax.xml.validation API. For DTDs, you have to use the regular SAX XMLReader class. However, you can install additional libraries that add support for these and other schema languages.

How schema factories are located

The Java programming language isn't limited to a single schema factory. When you pass a URI identifying a particular schema language to SchemaFactory.newInstance(), it searches the following locations in this order to find a matching factory:

  1. The class named by the "javax.xml.validation.SchemaFactory:schemaURL" system property
  2. The class named by the "javax.xml.validation.SchemaFactory:schemaURL" property found in the $java.home/lib/jaxp.properties file
  3. javax.xml.validation.SchemaFactory service providers found in the META-INF/services directories of any available Java Archive (JAR) files
  4. A platform default SchemaFactory, com.sun.org.apache.xerces.internal.jaxp.validation.xs.SchemaFactoryImpl in JDK 5

To add support for your own custom schema language and corresponding validator, all you have to do is write subclasses of SchemaFactory, Schema, and Validator that know how to process your schema language. Then, install your JAR in one of these four locations. This is useful for adding constraints that are more easily checked in a Turing-complete language like Java than in a declarative language like the W3C XML Schema language. You can define a mini-schema language, write a quick implementation, and plug it into the validation layer.


Error handlers

The default response from a schema is to throw a SAXException if there's a problem and do nothing if there isn't. However, you can provide a SAX ErrorHandler to receive more detailed information about the document's problems. For example, suppose you want to log all validation errors, but you don't want to stop processing when you encounter one. You can install an error handler such as that in Listing 3.

Listing 3. An error handler that merely logs non-fatal validity errors
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ForgivingErrorHandler implements ErrorHandler {

    public void warning(SAXParseException ex) {
        System.err.println(ex.getMessage());
    }

    public void error(SAXParseException ex) {
        System.err.println(ex.getMessage());
    }

    public void fatalError(SAXParseException ex) throws SAXException {
        throw ex;
    }

}

To install this error handler, you create an instance of it and pass that instance to the Validator's setErrorHandler() method:

  ErrorHandler lenient = new ForgivingErrorHandler();
  validator.setErrorHandler(lenient);

Schema augmentation

Some schemas do more than validate. As well as providing a true-false answer to the question of whether a document is valid, they also augment the document with additional information. For example, they can provide default attribute values. They might also assign types like int or gYear to an element or attribute. The validator can create such type-augmented documents and write them onto a javax.xml.transform.Result object. All you need to do is pass a Result as the second argument to validate. For example, Listing 4 both validates an input document and creates an augmented DOM document from the combination of the input with the schema.

Listing 4. Augmenting a document with a schema
import java.io.*;
import javax.xml.transform.dom.*;
import javax.xml.validation.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class DocbookXSDAugmenter {

    public static void main(String[] args) 
      throws SAXException, IOException, ParserConfigurationException {

        SchemaFactory factory 
         = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File schemaLocation = new File("/opt/xml/docbook/xsd/docbook.xsd");
        Schema schema = factory.newSchema(schemaLocation);
        Validator validator = schema.newValidator();
        
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(new File(args[0]));
        
        DOMSource source = new DOMSource(doc);
        DOMResult result = new DOMResult();
        
        try {
            validator.validate(source, result);
            Document augmented = (Document) result.getNode();
            // do whatever you need to do with the augmented document...
        }
        catch (SAXException ex) {
            System.out.println(args[0] + " is not valid because ");
            System.out.println(ex.getMessage());
        }  
        
    }

}

This procedure can't transform an arbitrary source into an arbitrary result. It doesn't work at all for stream sources and results. SAX sources can be augmented into SAX results, and DOM sources into DOM results; but SAX sources can't be augmented to DOM results or vice versa. If you need to do that, first augment into the matching result -- SAX for SAX and DOM for DOM -- and then use TrAX's identity transform to change the model.

This technique isn't recommended, though. Putting all the information the document requires in the instance is far more reliable than splitting it between the instance and the schema. You might validate, but not everyone will.


Type information

The W3C XML Schema Language is heavily based on the notion of types. Elements and attributes are declared to be of type int, double, date, duration, person, PhoneNumber, or anything else you can imagine. The Java Validation API includes a means to report such types, although it's surprisingly independent of the rest of the package.

Types are identified by an org.w3c.dom.TypeInfo object. This simple interface, summarized in Listing 5, tells you the local name and namespace URI of a type. You can also tell whether and how a type is derived from another type. Beyond that, understanding the type is up to your program. The Java language doesn't tell you what it means or convert the data to a Java type such as double or java.util.Date.

Listing 5. The DOM TypeInfo interface
package org.w3c.dom;

public interface TypeInfo {

  public static final int DERIVATION_RESTRICTION;
  public static final int DERIVATION_EXTENSION;
  public static final int DERIVATION_UNION;

  public String  getTypeName();
  public String  getTypeNamespace()
  public boolean isDerivedFrom(String namespace, String name, int derivationMethod);

}

To get TypeInfo objects, you ask the Schema object for a ValidatorHandler rather than a Validator. ValidatorHandler implements SAX's ContentHandler interface. Then, you install this handler in a SAX parser.

You also install your own ContentHandler in the ValidatorHandler (not the parser); the ValidatorHandler will forward the augmented events on to your ContentHandler.

The ValidatorHandler makes available a TypeInfoProvider that your ContentHandler can call at any time to find out the type of the current element or one of its attributes. It can also tell you whether an attribute is an ID, and whether the attribute was explicitly specified in the document or defaulted in from the schema. Listing 6 summarizes this class.

Listing 6. The TypeInfoProvider class
package javax.xml.validation;

public abstract class TypeInfoProvider {

  public abstract TypeInfo getElementTypeInfo();
  public abstract TypeInfo getAttributeTypeInfo(int index);
  public abstract boolean  isIdAttribute(int index);
  public abstract boolean  isSpecified(int index);

}

Finally, you parse the document with the SAX XMLReader. Listing 7 shows a simple program that uses all these classes and interfaces to print out the names of all the types of the elements in a document.

Listing 7. Listing element types
import java.io.*;
import javax.xml.validation.*;

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

public class TypeLister extends DefaultHandler {

    private TypeInfoProvider provider;
    
    public TypeLister(TypeInfoProvider provider) {
        this.provider = provider;
    }

    public static void main(String[] args) throws SAXException, IOException {

        SchemaFactory factory 
         = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File schemaLocation = new File("/opt/xml/docbook/xsd/docbook.xsd");
        Schema schema = factory.newSchema(schemaLocation);
    
        ValidatorHandler vHandler = schema.newValidatorHandler();
        TypeInfoProvider provider = vHandler.getTypeInfoProvider();
        ContentHandler   cHandler = new TypeLister(provider);
        vHandler.setContentHandler(cHandler);
        
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setContentHandler(vHandler);
        parser.parse(args[0]);
        
    }
    
    public void startElement(String namespace, String localName,
      String qualifiedName, Attributes atts) throws SAXException {
        String type = provider.getElementTypeInfo().getTypeName();
        System.out.println(qualifiedName + ": " + type);
    }

}

Here's the start of the output from running this code on a typical DocBook document:

book: #AnonType_book
title: #AnonType_title
subtitle: #AnonType_subtitle
info: #AnonType_info
copyright: #AnonType_copyright
year: #AnonType_year
holder: #AnonType_holder
author: #AnonType_author
personname: #AnonType_personname
firstname: #AnonType_firstname
othername: #AnonType_othername
surname: #AnonType_surname
personblurb: #AnonType_personblurb
para: #AnonType_para
link: #AnonType_link

As you can see, the DocBook schema assigns most elements anonymous complex types. Obviously, this will vary from one schema to the next.


Conclusion

The world would be a poorer place if everyone spoke just one language. Programmers would be unhappy if they had only one programming language to choose from. Different languages suit different tasks better, and some tasks require more than one language. XML schemas are no different. You can choose from a plethora of useful schema languages. In Java 5 with javax.xml.validation, you have an API that can handle all of them.

Resources

Learn

  • Kicking back with RELAX NG (David Mertz, developerWorks, February, 2003) introduces you to the RELAX NG schema language.
  • A hands-on introduction to Schematron (Uche Ogbuji, developerWorks, September, 2004) introduces the Schematron schema language in this tutorial.
  • Chapter 20 of the XML 1.1 Bible (Elliotte Rusty Harold; Wiley, 2003) is a complete introduction to the W3C XML Schema Language.
  • XML in a Nutshell (Elliotte Rusty Harold and W. Scott Means, O'Reilly, 2005) includes a complete reference and a brief tutorial on the W3C XML schema language, as well as DOM and TrAX.
  • Processing XML with Java (Elliotte Rusty Harold, Addison-Wesley, 2002) explains how to use DOM, SAX, TrAX, and other APIs to access XML from Java.
  • The Java technology zone on developerWorks provides hundreds of articles about every aspect of Java programming.
  • The developerWorks XML zone includes a wide range of technical articles and tips, tutorials, standards, and IBM Redbooks.
  • Find out how to become an IBM-Certified Developer for XML and related technologies.

Get products and technologies

  • DocBook 5.0 is normatively defined in RELAX NG. The RELAX NG schema is then compiled into DTDs and W3C schemas for users who need those languages.
  • Download JAXP 1.3 for Java 1.3 and 1.4 from java.net.
  • Kohsuke Kawaguchi has written an adapter layer that connects the older JARV interface supported by several RELAX NG validators such as JING to the JAXP APIs described here.
  • The Xerces XML parser supports JAXP 1.3, including the validation API discussed in this article.
  • IBM trial software is available for download directly from developerWorks.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
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. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

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.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

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

 


All information submitted is secure.

Dig deeper into XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Java technology
ArticleID=150911
ArticleTitle=The Java XML Validation API
publish-date=02102010