JAXB Marshall and Unmarshal from Generated Classes

March 27, 2018

Given classes generated from an XML Schema via a Maven plugin, the following code can be used to serialise to and from XML.

Unmarshal XML into classes

JAXBContext jc = JAXBContext.newInstance(GeneratedClass.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
GeneratedClass javaObject = (GeneratedClass)unmarshaller.unmarshal(new StringReader(xml));

Marshal Java class to XML

JAXBContext jaxbContext = JAXBContext.newInstance(GeneratedClass.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(javaObject, sw);
String xml = sw.toString();

The above doesn't work if there is no @XmlRootElement annotation, giving the exception com.sun.istack.internal.SAXException2: unable to marshal type "GeneratedClass" as an element because it is missing an @XmlRootElement annotation This alternative seems to work, specifying the namespace and tag name for the root node with a QName:

StringWriter sw = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
JAXBElement<GeneratedClass> wrappedClass = new JAXBElement<>(new QName("", "RootNode"), GeneratedClass.class, response);
jaxbMarshaller.marshal(wrappedResponse, sw);
String messageAsXml = sw.toString();