Monday, May 4, 2015

JAXB Marsheller an Object, that doesn't have Root Element

import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.MarshalException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;

public class JaxbMarshallWithoutRootElement {

    private static String marshal(Object obj, String packageStr) throws Exception {
        String str = null;
        StringWriter stringWiter = null;
        try {
               JAXBContext ctx = JAXBContext.newInstance(packageStr);
               QName qName = new QName(obj.getClass().getSimpleName());
               JAXBElement jx = new JAXBElement(qName, obj.getClass(), obj);
               Marshaller marshaller = ctx.createMarshaller();
               marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
               /*marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "");
               marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");*/

               stringWiter = new StringWriter();
               marshaller.marshal(jx, stringWiter);
               str = stringWiter.getBuffer().toString();

        } catch (MarshalException e) {
               throw e;
        } catch (Exception e) {
               throw e;
        } finally {
               if (stringWiter != null) {
                   stringWiter.close();
               }
        }
        return str;
    }
}