How to Validate Against an XML Schema
A XML Schema allows more restrictions than Java's object model. For example, Java does not allow you to limit the length of a string. If you have a XML schema, you can let JAXB check the XML during the transformation process to be sure that the input and output is valid. First, you need to create a Schema instance (javax.xml.validation package):
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(new File("schema1.xsd")));
Now that you have the Schema, just set the property in the Marshaller to validate the generated XML:
MovieLibrary library = ...;
JAXBContext ctx = JAXBContext.newInstance(MovieLibrary.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setSchema(schema);
marshaller.marshal(new JAXBElement<MovieLibrary>(new QName("movieLibrary"),
MovieLibrary.class, library),
new FileOutputStream("/tmp/library.xml"));
To validate XML before you read it, set the schema property in the Unmarshaller:
JAXBContext ctx = JAXBContext.newInstance(MovieLibrary.class); // can be reused
Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setSchema(schema);
MovieLibrary library = unmarshaller.unmarshal(new StreamSource(new File("/tmp/library.xml")),
MovieLibrary.class).getValue();
Reading or writing an invalid document causes JAXB to throw an exception.