简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM