JAXB marshal 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 marshal schema validation during marshal operation. Here is a way to leverage the JAXB APIs.

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

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 marshal schema validation
JAXB marshal schema validation

then you get java file

Customize the JAXB ValidationEventHandler

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 marshal schema validation

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

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

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


Leave a Comment


Please share it if you found this useful
Hide Buttons