开发者

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.

  1. what is the best w开发者_C百科ay to do it ?

  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜