JAXB unmarshal schema validation

In a How to validate XML versus XSD in Java tutorial shows you how to validate an validate xml vs xsd file using the javax.xml.validation APIs. In this tutorial shows you how to use JAXB unmarshal schema validation during unmarshal operation. Here is a way to leverage the JAXB APIs.

Such as the previous tutorial, you should define Fruit XML schema
Fruit.xsd

Here, you should use a java model that may be generated by JAXB in Eclipse such as the below figure (you could define manually this model by yourself)

JAXB unmarshal schema validation
JAXB unmarshal schema validation

then you get java file

Customize the ValidationEventHandler of JAXB

ValidationEventHandler catches all events that JAXB reports after finished validation. The event is an instance of ValidationEvent, and provides many details about the validation issue. You could get these details also by using SAXParseException. Here, the CustomValidationEventHandler will get information of all events and print the formatted messages.

JAXB unmarshal schema validation

The validation will be activated when the unmarshal operation starts. To catch the events you must set a instance of ValidationEventHandler for a unmarshal instance.

Validation input Fruit.xml
The Fruit.xml is input for this validation demo

OKay, now you run the main class UnmarshalXMLValidation and here is output:

That’s all on how to do JAXB unmarshal schema validation. You can download this program source code

UnmarshalSchemaValidate

Leave a Comment

*

Please share it if you found this useful
Hide Buttons