Thursday, June 14, 2012

JAXB schema validation

Say you have defined an xsd, which has certain restrictions in elements.  You would expect that marshaling the instance will execute the restrictions that are defined in the schema. These restrictions could be like pattern matches, length restriction, etc.  Well, it doesn't enforce those restrictions.
In order to get these restrictions enforced, do the following

 public static void validateJAXBObject(@SuppressWarnings("rawtypes") Class jaxbClass, Object instance) throws JAXBException, SAXException  
   {  
     JAXBContext jaxbContext = getContext(jaxbClass);  
     Marshaller marshaller = jaxbContext.createMarshaller();  
     SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);  
     Schema schema = factory.newSchema(jaxbClass.getResource(<xsd_file>));  
     marshaller.setSchema(schema);  
     marshaller.marshal(instance, new StringWriter());  
   }  

No comments:

Post a Comment