Here you can find the source of marshalToString(T obj, Class
public static <T> String marshalToString(T obj, Class<T> clazz, QName qname) throws javax.xml.bind.JAXBException, java.io.IOException
//package com.java2s; //License from project: Apache License import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; public class Main { public static <T> String marshalToString(T obj, Class<T> clazz, QName qname) throws javax.xml.bind.JAXBException, java.io.IOException { java.io.StringWriter sw = new java.io.StringWriter(); javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(clazz.getPackage().getName()); javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(new JAXBElement(qname, clazz, obj), sw); sw.close();//from w w w .ja v a 2 s. c om return sw.toString(); } }