October 7, 2008

Using Jaxb2Marshaller to Write Object to file on disk

So i been using jaxb XML annotation and spring OXM unmarshaller to read XML files into objects but i needed to do write (serialize) an object to xml and write it to a file... I spend about 1/2 hour on google but no luck. With a help of a co-worker i was able to get it to work... here is the code

public static void main(String[] args) throws Exception {
        Jaxb2Marshaller marshaller = (Jaxb2Marshaller) factory.getBean("xmlMarshaller");
        DOMResult result = new DOMResult();
        marshaller.marshal(myObject, result);
        Document doc = (Document) result.getNode();
        writeXmlFile(doc, "src/main/resources/autogen/file.xml");

Note the last part was taken from The Java Developers Almanac 1.4

    // This method writes a DOM document to a file
    public static void writeXmlFile(Document doc, String filename) {
        try {
            // Prepare the DOM document for writing
            Source source = new DOMSource(doc);

            // Prepare the output file
            File file = new File(filename);
            Result result = new StreamResult(file);

            // Write the DOM document to the file
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {


I hope this helps...