Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.xml.sax.SAXException; public class Main { private static final HashMap<String, JAXBContext> marshallContexts = new HashMap<String, JAXBContext>(); public static void marshall(String cntxtPkg, Object obj, OutputStream out) throws JAXBException, SAXException, IOException { Marshaller marshaller = createMarshall(cntxtPkg); if (marshaller == null) return; marshaller.marshal(obj, out); } private static Marshaller createMarshall(String pkgName) throws JAXBException { JAXBContext jaxbCtx = null; if ((jaxbCtx = marshallContexts.get(pkgName)) == null) { jaxbCtx = JAXBContext.newInstance(pkgName); marshallContexts.put(pkgName, jaxbCtx); } Marshaller marshaller = jaxbCtx.createMarshaller(); return marshaller; } }