Saturday, February 26, 2011

Quick Java code to convert a Java object into XML

I keep having to do it and I keep forgetting...

private static String objectToXML(Object object, Class clazz) throws JAXBException,
 PropertyException {

 JAXBContext jc = JAXBContext.newInstance(clazz);
 Marshaller marshaller = jc.createMarshaller();
 marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
 ByteArrayOutputStream baos = new ByteArrayOutputStream();   
 marshaller.marshal(object, baos);
 return new String(baos.toByteArray());

No comments: