Java tutorial
//package com.java2s; import java.io.StringWriter; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Main { private static Map<Class<?>, Marshaller> JAXB_MARSHALLER_CACHE = new ConcurrentHashMap<Class<?>, Marshaller>(); public static String toXml(Object jaxbElement) { return toXml(jaxbElement, null); } public static String toXml(Object jaxbElement, Map<String, Object> marshallerProps) { try { StringWriter stringWriter = new StringWriter(); Marshaller marshaller = getJaxbMarshaller(jaxbElement.getClass(), marshallerProps); // OutputFormat xmlOutputFormat = new OutputFormat(); // xmlOutputFormat.setCDataElements(new String[] {"^id"}); // xmlOutputFormat.setPreserveSpace(true); // xmlOutputFormat.setIndenting(true); // XMLSerializer xmlSerializer = new XMLSerializer(xmlOutputFormat); // xmlSerializer.setOutputByteStream(System.out); // marshaller.marshal(jaxbElement, xmlSerializer.asContentHandler()); marshaller.marshal(jaxbElement, stringWriter); return stringWriter.toString(); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } } private static Marshaller getJaxbMarshaller(Class<?> classesToBeBound, Map<String, Object> marshallerProps) throws Exception { Marshaller marshaller = JAXB_MARSHALLER_CACHE.get(classesToBeBound); if (marshaller == null) { JAXBContext jaxbContext = JAXBContext.newInstance(classesToBeBound); marshaller = jaxbContext.createMarshaller(); if (marshallerProps != null && marshallerProps.size() > 0) { for (Map.Entry<String, Object> prop : marshallerProps.entrySet()) { marshaller.setProperty(prop.getKey(), prop.getValue()); } } JAXB_MARSHALLER_CACHE.put(classesToBeBound, marshaller); } return marshaller; } }