How to use XML schema to validate @ResponseBody ordered by JAXB

I have a system returning many XML files using @ResponseBody and @ XmlElement-sorting (JAXB).

What is the best way to validate the resulting XML using the generated schema?

I still need to run the elements and test them, but validating the XML schema will make the second part very easy.


source to share

2 answers

Spring makes this easy for you (if you are using Jaxb2Marshaller):

<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
  <property name="schema" value="file:/some/path/schema.xsd"/>




Setting up XSD schema for marshaler and unmarshaller JAXB:

SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
InputStream schemaStream = openMySchemaFileStream();
Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));    


Validate the XML string by splitting it:

Reader reader = new StringReader(xml);
StreamSource source = new StreamSource(reader);
unmarshaller.unmarshal(source, YourJAXBClass.class);


Validate a JAXB object by sorting by SAX 'DefaultHandler, which does nothing:

marshaller.marshal(obj, new DefaultHandler());




All Articles