Java examples for XML:JAXB
Marshal object to File
//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 { public static void toFile(Object objJAXB, String dir, String fileName) throws Exception { marshalToFile(objJAXB, dir + File.separator + fileName); }/*from www . ja v a2 s . c o m*/ 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); } }