Java tutorial
//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 { private static Map<Class<?>, Marshaller> mMap = new HashMap<Class<?>, Marshaller>(); /** * Object to XML * * @param object * @return */ public static String convertToXML(Object object) { try { System.out.println(mMap.containsKey(object.getClass()) + "---mmap-----"); if (!mMap.containsKey(object.getClass())) { JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // marshaller.setProperty(CharacterEscapeHandler.class.getName(), // new CharacterEscapeHandler() { // public void escape(char[] ac, int i, int j, boolean // flag,Writer writer) throws IOException { // writer.write( ac, i, j ); } // }); mMap.put(object.getClass(), marshaller); } System.out.println("----mmap--" + mMap.toString()); StringWriter stringWriter = new StringWriter(); mMap.get(object.getClass()).marshal(object, stringWriter); return stringWriter.getBuffer().toString(); } catch (JAXBException e) { e.printStackTrace(); } return null; } public static String convertToXml(Object obj, String encoding) { String result = null; try { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); // marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); // marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, true); StringWriter writer = new StringWriter(); marshaller.marshal(obj, writer); result = writer.toString(); } catch (Exception e) { e.printStackTrace(); } return result; } }