validate xml file against xml schema
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.
what is the best w开发者_C百科ay to do it ?
can someone give a simple example of how to do it ?
Appreciate your help.
Thanks, Alo
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.
精彩评论