A little bit of history
XML processing in Java has come a long way in the last ten years. Back in the old days mapping XML to Java was a bit of a nightmare, deserialising usually meant pulling the DOM apart bit by bit to get at the interesting parts. Serialisation was worse – the Java DOM API is truly horrific. Helper libraries existed, JDOM, XMLBeans etc etc but while they made things somewhat easier they never made it easy. Add to that the problems introduced by having various versions of xerces, various implementations of the org.w3c.dom API, and versions of the DOM api itself (urgh – dom level 2 anyone?) it added up to development hell.
Now days, there’s a plethora of libraries and methods to choose from and some of them are baked right into the core java class libraries. JAXB is one of them. JAXB comes with a handy little command line tool called xjc, which takes a schema and spits out an annotated class hierarchy. The class hierarchy behaves in a sane manner (unlike the weird stuff XMLBeans used to make) and can be used for marshalling and unmarshalling XML to POJOs.
Generating Java classes from an XML schema is easy. It goes a little something like this:
bash> xjc my-schema.xsd
Yup, it’s usually that simple. To generate it in the package you want, you can do
bash> xjc -p my.pkg my-schema.xsd
Place the generated classes somewhere in your project and you’re ready to go.
In the simplest cases you can do something as easy as:
//XML to POJO...
JAXBContext context = JAXBContext.newInstance(MyRootElement.class);
Unmarshaller um = context.createUnmarshaller();
MyRootElement obj = (MyRootElement) um.unmarshal(new StringReader(xmlString));
//and back again...
StringWriter xmlOutput = new StringWriter();
While there’s loads more to JAXB than this example shows, this will certainly get you started. I wrote the ORCiD Java Library using xjc and JAXB, so if you’re interested, check it out.