Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; public class Main { /** * Salva um objeto xml JAX-B em um arquivo .xml * @param objJAXB * @param dir * @param fileName * @throws Exception */ public static void toFile(Object objJAXB, String dir, String fileName) throws Exception { marshalToFile(objJAXB, dir + File.separator + fileName); } private static void marshalToFile(Object objJAXB, String fullFileName) throws Exception { newMarshaller(objJAXB.getClass()).marshal(objJAXB, new File(fullFileName)); } private static String marshal(Object objJAXB) throws Exception { ByteArrayOutputStream result = new ByteArrayOutputStream(); newMarshaller(objJAXB.getClass()).marshal(objJAXB, newWriter(result)); return result.toString(); } private static Marshaller newMarshaller(Class<?> classJAXB) throws Exception { return newContext(classJAXB).createMarshaller(); } private static XMLStreamWriter newWriter(ByteArrayOutputStream result) throws Exception { XMLOutputFactory output = XMLOutputFactory.newInstance(); XMLStreamWriter writer = output.createXMLStreamWriter(result); return writer; } private static JAXBContext newContext(Class<?> classJAXB) throws Exception { return JAXBContext.newInstance(classJAXB); } }