Java – how to use JAXB to validate XML schema?
I am using XML and JAXB because I ungroup and group XML into Java objects and vice versa Now I try to validate our XML against our schema (test. XSD) Suppose that if any required fields are missing from my XML, I want to know how to test the schema Which field is missing after XSD validates the XML
public void unmarshal(final InputStream is) { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(is); Object req = unmarshaller.unmarshal(reader); // how would I validate here? }
How will I validate my XML with test XSD mode My test The XSD schema path is –
Update: test XSD is loaded as:
Schema schema = factorySchema.newSchema(new File("C:\\workspace\\one\\two\\three\\src\\main\\java\\com\\package\\serv\\ap\\versionOne\\test.xsd"));
Solution
Before you release the blockade, you only need to set up a javax on the unmarshaller xml. validation. An instance of schema You can specify the implementation of validationeventhandler on the unmarshaller to capture any problems that occur during unmarshalling
> http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/Unmarshaller.html#setSchema%28javax.xml.validation.Schema%29
Learn more
I wrote more about this use case on my blog:
> http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html