Marshal Java object to a file : JAXB « XML « Java Tutorial


import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;

public class JavaToXMLDemo {
  public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Employee.class);

    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Employee object = new Employee();

    m.marshal(object, new FileOutputStream("result.xml"));


class Employee {
  private String code;

  private String name;

  private int salary;

  public String getCode() {
    return code;

  public void setCode(String code) {
    this.code = code;

  public String getName() {
    return name;

  public void setName(String name) { = name;

  public int getSalary() {
    return salary;

  public void setSalary(int population) {
    this.salary = population;

33.9.1.XMLSchema Mapping Annotations
33.9.2.The xjc Tool
33.9.3.Marshal Java object to xml and output to console
33.9.4.Marshal Java object to a file