Full circle: POJO to XSD to JAXB Generated Object

I have been exploring the most simple ways to serialise / generate XML from a POJO. I have used XStream a few years ago but wanted to try the JAXB Marshaller instead.

I added some @XmlRootElement annotations to my POJO and child POJO (I guess making them less POJO like in the process).

Then the @XmlTransient annotation had to be added to the child’s parent reference in order to avoid the “A cycle is detected in the object graph. This will cause infinitely deep XML” error and make JAXB ignore this reference on serialization.

Generating XML at that point was pretty simple:

java.io.StringWriter xmlSW = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(myPojo.getClass()); Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.marshal(myPojo, xmlSW);
log.debug("Our XML: " + xmlSW.toString());

Then to get the XSD and write it system.out:

java.io.StringWriter xsdSW = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(myPojo.getClass());
final List results = new ArrayList();
jaxbContext.generateSchema(
new SchemaOutputResolver(){

@Override
public Result createOutput(String ns, String file)
throws IOException {
DOMResult result = new DOMResult();
result.setSystemId(file);
results.add(result);
return result;
}
});


DOMResult domResult = results.get(0);
Document doc = (Document) domResult.getNode();
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
XMLSerializer serializer = new XMLSerializer(xsdSW, format);
serializer.serialize(doc);

log.debug("Our XSD: " + xsdSW.toString());

The cool thing that can be done now with the XSD is to run it through the JAXB generator which will re-create the parent and child classes automatically, with even more (somewhat assumed) annotations.

Just thought it was a cool how you can go from POJO to XML/XSD back to a POJO relatively easily. Sort of similar to what you can do with WSDLs and creating web services and web service client’s with skeleton code around them using JAXB.