Java tutorial
//package com.java2s; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.namespace.QName; public class Main { private static Map<Class<?>, JAXBContext> contextCache = new HashMap<>(); /** * Marshals a bean to XML. * * @param bean * @return XML {@link String} * @throws JAXBException */ public static <T> String marshal(T bean) throws JAXBException { StringWriter stw = new StringWriter(); createMarshaller(bean.getClass()).marshal(bean, stw); return stw.toString(); } /** * Marshals a bean to XML. * * @param bean * @param namespaceURI * @param localPart * @return XML {@link String} * @throws JAXBException */ @SuppressWarnings("unchecked") public static <T> String marshal(T bean, String namespaceURI, String localPart) throws JAXBException { QName qName = new QName(namespaceURI, localPart); Class<T> clazz = (Class<T>) bean.getClass(); Marshaller marshaller = createMarshaller(clazz); Writer stw = new StringWriter(); marshaller.marshal(new JAXBElement<T>(qName, clazz, bean), stw); return stw.toString(); } /** * Creates a {@link Marshaller} for the given {@link Class}. * * @param clazz {@link Class} * @return {@link Marshaller} * @throws JAXBException */ private static <T> Marshaller createMarshaller(Class<T> clazz) throws JAXBException { return getContext(clazz).createMarshaller(); } /** * Returns the corresponding {@link JAXBContext} for the given {@link Class}. * * @param clazz {@link Class} * @return {@link JAXBContext} * @throws JAXBException */ private static <T> JAXBContext getContext(Class<T> clazz) throws JAXBException { synchronized (contextCache) { if (!contextCache.containsKey(clazz)) { contextCache.put(clazz, JAXBContext.newInstance(clazz)); } } return contextCache.get(clazz); } }