Java examples for XML:JAXB
Convert Object to XML via JAXB
//package com.java2s; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class Main { public static void main(String[] argv) throws Exception { Object object = "java2s.com"; System.out.println(convertToXML(object)); }/*w w w . j ava 2 s . co m*/ private static Map<Class<?>, Marshaller> mMap = new HashMap<Class<?>, Marshaller>(); /** * Object to XML * @param object * @return */ public static String convertToXML(Object object) { try { if (!mMap.containsKey(object.getClass())) { JAXBContext jaxbContext = JAXBContext.newInstance(object .getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); mMap.put(object.getClass(), marshaller); } StringWriter stringWriter = new StringWriter(); mMap.get(object.getClass()).marshal(object, stringWriter); return stringWriter.getBuffer().toString(); } catch (JAXBException e) { e.printStackTrace(); } return null; } }