Sunday, August 17, 2014

JAXB Validation using Schema

JAXB supports validation. It can validation an XML document before it is converted into Java object model.For validating the XML document register the schema with the unmarsheller. Schema also called as XSD contains the definiton of XML files. For example it will tell which attributes an element contains of what kind of sub elements are present as child of an element.

//Setting the Validation
Schema schema;
SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );

//Provide the XSD. XSD is XML Schema definition
schema = schemaFactory.newSchema(new File("src/user_jaxb.xsd"));

Another simple way is to register an EventHandler. A default Event handler is also provided.

//Enable the validation handler
unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());

For customizing the validation messages a ValidationEventcollector is registered with the unmarshaller. The parsing fails at the moment the first exception is encountered. The code below might look that all the exceptions are collected at once but in reality the parsing stops the moment the first exception is encountered

//If the message regarding validation to be customized        
ValidationEventCollector validationCollector =
                              new ValidationEventCollector();
unmarshaller.setEventHandler( validationCollector );

The message can be customized by iterating on the ValidationEventCollector

for( ValidationEvent event: validationCollector.getEvents() ){
    String msg = event.getMessage();
    ValidationEventLocator locator = event.getLocator();
    int line = locator.getLineNumber();
    int column = locator.getColumnNumber();
    System.out.println("Error at line " + line + " column "+ column );

No comments:

Post a Comment