Javaton

Friday, April 14, 2006

JAXB 2 - Validate against XML Schema

Recently, java.net announced the availability of JAXB 2 RI. Although there is a short tutorial that aims to introduce JAXB the part that reffers to the validation of XML against XML Schema reffers to JAXB 1.
The tutorial states that in order to validate xml the following option should be set:
unmarshaller.setValidating(true);
In JAXB 2 this method is deprecated and throws a UnsupportedOperationException when called.

So, here is how you validate against XML Schema using JAXB2:

import javax.xml.*;
import javax.xml.validation.*;
..
// Get a schema factory for XML Schema
SchemaFactory schemaFactory =
SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

// In this example we use two xsd files
Source schemas = new Source[]{
new StreamSource(new File("schema1.xsd")),
new StreamSource(new File("schema2.xsd"))
};

// Obtain schema
Schema schema = schemaFactory.newSchema(schemas);

// Enable schema validation
unmarshaller.setSchema(schema);

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home