// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package xmlproc;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JAXB {
    private final static String XML_FILE = "/work/employees.xml";
    public static void main(String[] args) throws Exception {
        // setup context
        JAXBContext jxbctx = JAXBContext.newInstance(Employees.class);
        // read from file
        Unmarshaller um = jxbctx.createUnmarshaller();
        Employees employees = (Employees)um.unmarshal(new FileInputStream(XML_FILE));
        // add employee
        employees.getList().add(new Employee(4, "Dave D", "Intern"));
        // write out
        Marshaller m = jxbctx.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        OutputStream os = new FileOutputStream("/work/employees2.xml");
        m.marshal(employees, os);
        os.close();
    }
}
