Here you can find the source of marshalToString(Object obj)
public static String marshalToString(Object obj) throws JAXBException
//package com.java2s; //## The MIT License import java.io.StringWriter; import java.util.concurrent.ConcurrentHashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; public class Main { private static ConcurrentHashMap<Class<?>, JAXBContext> contextMap = new ConcurrentHashMap<Class<?>, JAXBContext>(); private static javax.xml.parsers.DocumentBuilderFactory dbf; public static String marshalToString(Object obj) throws JAXBException { StringWriter writer = new StringWriter(); JAXBContext jc = getContext(obj.getClass()); Marshaller marshaller = jc.createMarshaller(); marshaller.marshal(obj, writer); return writer.toString(); }//from w w w . j av a2s. c om private static JAXBContext getContext(Class<?> c) throws JAXBException { JAXBContext jc = contextMap.get(c); if (jc == null) { jc = JAXBContext.newInstance(c); contextMap.put(c, jc); } return jc; } public static org.w3c.dom.Element marshal(Object obj) throws JAXBException { try { Document doc = null; JAXBContext jc = getContext(obj.getClass()); Marshaller marshaller = jc.createMarshaller(); doc = dbf.newDocumentBuilder().newDocument(); marshaller.marshal(obj, doc); return doc.getDocumentElement(); } catch (ParserConfigurationException ex) { throw new JAXBException("Error in creating document elements: " + ex.getMessage()); } } }