3

I have a system returning a lot of XMLs using @ResponseBody and @XmlElement marshalling (JAXB).

What is the best way to validate the resulting XML using a created Schema?

I still need to run through the elements and test those, but a XML Schema validation would make the second part really easy.

mamruoc
  • 847
  • 3
  • 11
  • 21

2 Answers2

2

Spring makes this easy for you (assuming you use the Jaxb2Marshaller):

<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
  <property name="schema" value="file:/some/path/schema.xsd"/>
</bean>
Kevin Schmidt
  • 2,111
  • 2
  • 14
  • 12
  • I am pretty new to Spring, but how do I specify which xsd to which `@ResponseBody` which is what I need to test (controller returns a marshalled XML based on combined models) – mamruoc Mar 22 '12 at 21:49
  • Oki, I've added ``, instead of adding `classesToBeBound`, I have used http://www.walgemoed.org/2010/12/jaxb2-spring-ws/. However, everything runs nicely, in the sense, even invalid xsd does not give any error message – mamruoc Mar 23 '12 at 08:38
  • Check out http://www.ibm.com/developerworks/web/library/wa-restful/ (Listing 4) for an example how to set up a http marshaling converter and give it the above marshaller. – Kevin Schmidt Mar 23 '12 at 11:12
  • Mm... I'll have a look it at. Thanks – mamruoc Mar 23 '12 at 14:59
1

Setup XSD schema for JAXB marshaller and unmarshaller:

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

Validate XML string by unmarshalling it:

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

Validate JAXB object by marshalling to SAX' DefaultHandler, that does nothing:

marshaller.marshal(obj, new DefaultHandler());
alexkasko
  • 4,855
  • 1
  • 26
  • 31