Java tutorial
//package com.java2s; import java.io.OutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.PropertyException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; public class Main { public static <T> void marshal(Object jaxbElement, Class<T> jaxbFactory, OutputStream out) throws JAXBException { if (!(jaxbElement instanceof JAXBElement<?>)) { throw new JAXBException("Must be a instance of JAXBElement<?>"); } try { JAXBContext jc = JAXBContext.newInstance(jaxbFactory); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(jaxbElement, out); } catch (PropertyException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } } public static <T> Document marshal(Object jaxbElement, Class<T> jaxbFactory) throws JAXBException { if (!(jaxbElement instanceof JAXBElement<?>)) { throw new JAXBException("Must be a instance of JAXBElement<?>"); } Document doc = null; try { JAXBContext jc = JAXBContext.newInstance(jaxbFactory); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.newDocument(); marshaller.marshal(jaxbElement, doc); } catch (PropertyException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return doc; } }