« June 2008 | Main | December 2010 »

October 15, 2009

JAXB2: Marshalling fails due to validation, but you can't see the error

Having used JAXB2 to construct a tree of XML from objects, you try and marshall your objects to XML, only to find you get an Exception telling you your resulting XML has failed validation. But as you cannot see the generated XML, you have no way to see where you've gone wrong.

Stuck?

JAXB2 has a deprecated the javax.xml.bind.Validator class, and the person who documented this didn't bother to document the mechanism to replace it.

What I did manage to find was the javax.xml.bind.util.ValidationEventCollector class, which you can add to your Marshaller object, like this:

			ValidationEventCollector collector = new ValidationEventCollector();
			marshaller.setEventHandler(collector);

Now the marshaling works! And your errors can be retrieved from ValidationEventCollector, like this:

			collector.getEvents();

Hopefully this will save someone some pain.