views:

319

answers:

1

Hi, this is about validating a XML file (eg: marshalledfile.xml) against a XML schema (eg: schemafile.xsd). we are using jaxb to marshall java objects into into a xml file.

  1. what is the best way to do it ?

  2. can someone give a simple example of how to do it ?

Appreciate your help.

Thanks, Alo

+3  A: 

You can set the Schema directly in the Marshaller. 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 = ...; // <-- your JAXB-annotated tree

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"));

See also "How to Validate Input against an XML Schema?" in the Jarfiller JAXB Guide.

Tim Jansen