save/Marshall Object to file by JAXB - Java XML

Java examples for XML:JAXB

Description

save/Marshall Object to file by JAXB

Demo Code


//package com.java2s;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {


    public final static void save(Object object, String path) {
        try {/*from w ww .j a  v  a  2 s  .  c om*/
            File file = new File(path);
            JAXBContext jaxbContext = JAXBContext.newInstance(object
                    .getClass());
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    true);
            jaxbMarshaller.marshal(object, file);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials