Friday, August 19, 2011

Unmarshal an object using JAXB

The code below can be used to Unmarshal XML that comes in as a String value to an Object (Assuming that JAXB was used to create your classes from the Schema).

String theXMLString = " ... your XML saved as a String value ... ";
MyObject myObject = null;
try {
     //"mypackage" is the package where JAXB created the schema classes
    final JAXBContext jaxbContext = JAXBContext.newInstance("mypackage");
    final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    final ByteArrayInputStream byteStream = new        ByteArrayInputStream(theXMLString.getBytes());
    myObject = (MyObject) unmarshaller.unmarshal(byteStream);
} catch (JAXBException e) {
    System.out.println("An error has occurred: "+e.getMessage(), e);
}