Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class Main { /** * Marshal a jaxb object to obtain the xml format as a string. * * @param jabxbObject the jaxb object * @param jaxbContextName the contect name where to look to find jaxb classes * @param cl : {@link ClassLoader} of the ObjectFactory * @return a string representing the jaxb object * @throws JAXBException */ public static String marshal(Object jabxbObject, String jaxbContextName, ClassLoader cl) throws JAXBException { Marshaller marshaller = createMarshaller(jaxbContextName, cl); final ByteArrayOutputStream xmlStream = new ByteArrayOutputStream(); marshaller.marshal(jabxbObject, xmlStream); return xmlStream.toString(); } /** * Marshal a jaxb object to obtain the xml format as a string in specific encoding. * * @param jabxbObject the jaxb object * @param jaxbContextName the contect name where to look to find jaxb classes * @param cl : {@link ClassLoader} of the ObjectFactory * @return a string representing the jaxb object * @throws JAXBException * @throws UnsupportedEncodingException */ public static String marshal(Object jabxbObject, String jaxbContextName, ClassLoader cl, String encoding) throws JAXBException, UnsupportedEncodingException { Marshaller marshaller = createMarshaller(jaxbContextName, cl); final ByteArrayOutputStream xmlStream = new ByteArrayOutputStream(); marshaller.marshal(jabxbObject, xmlStream); return xmlStream.toString(encoding); } public String marshal(Object object) throws JAXBException, UnsupportedEncodingException { return marshal(object, object.getClass().getPackage().getName(), object.getClass().getClassLoader(), "UTF-8"); } /** * Create a {@link Marshaller} for the given context and return it. * * @param jaxbContextName the context name where to look to find jaxb classes * @param cl : {@link ClassLoader} of the ObjectFactory * @return the created {@link Marshaller} * @throws JAXBException */ public static Marshaller createMarshaller(final String jaxbContextName, ClassLoader cl) throws JAXBException { final JAXBContext jaxbContext = JAXBContext.newInstance(jaxbContextName, cl); return jaxbContext.createMarshaller(); } }