JAXB Validation


This tutorial explains how to use JAXB validation. It first shows how to validate a JAXB object marshalled to XML. It then shows how to validate an XML message unmarshalled to a Java object. It finally explains how to leverage the javax.xml.validation API to validate a Java object against an XML Schema.

This tutorial is part of a series of articles on JAXB:

The Domain Model

All the examples in this section use the following XML Schema for validation (company.xsd):

The Company entity has a name and a list of countries. The company.xsd, however, sets the restriction that a company can only have a maximum of three countries.

This is the Java annotated class:

Marshalling Validation

The javax.xml.bind.Marshaller interface has two methods that enable validation:

The setSchema() method takes as parameter a javax.xml.validation.Schema. The Schema class is an XML Schema that can be used for validation.

The setEventHandler() method takes a ValidationEventHandler that will handle all validation errors.  If the handleEvent() method returns true, the marshaller will continue with the processing. If it returns false, it will abort it.

This is the complete MashallingDemo:

When executed, it will print the following validation error to the console, as the company has four countries, one more than allowed.

Unmarshalling Validation

Unmarshalling validation is very similar to Marshalling validation. The javax.xml.bind.Unmarshaller interface also has a setSchema() and setEventHandler() methods that work the same way.

This is the XML that will be unmarshalled. It will fail validation as it has four countries.

And this is the UnmarshallingDemo:

When executed, it generates the same error as the marshalling example:

Validating JAXB with javax.xml.validation.Validator

JAXB can use the javax.xml.validation APIs to check the validity of Java classes against an XML Schema.

The validation takes place in a javax.xml.validation.Validator object. Validators are created from a javax.xml.validation.Schema object, which is the representation of an XML Schema. A validator accepts multiple XML inputs, represented by the javax.xml.transform.Source interface. Java provides several implementations such as DOMSource, JAXBSource, SAXSource, StAXSource and StreamSource.  To validate a JAXB Java object, you need to use JAXBSource.

It is also worth noting that validation errors are raised into an org.xml.sax.ErrorHandler.

This is the ValidationDemo:


The following two tabs change content below.

Eduard Manas

Eduard is a senior IT consultant with over 15 years in the financial sector. He is an experienced developer in Java, C#, Python, Wordpress, Tibco EMS/RV, Oracle, Sybase and MySQL.Outside of work, he likes spending time with family, friends, and watching football.

Latest posts by Eduard Manas (see all)

Leave a Reply