Marshal Java object to a file : JAXB « JDK 6 « Java






Marshal Java object to a file

 

import java.io.FileOutputStream;

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();
    object.setCode("CA");
    object.setName("Cath");
    object.setSalary(300);

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

  }
}

@XmlRootElement
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) {
    this.name = name;
  }

  public int getSalary() {
    return salary;
  }

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

        








Related examples in the same category

1.simple jaxb
2.Marshal Java object to xml and output to console
3.JAXB Demo
4.From XML Schema to Java Generic List
5.JAXB XML Schema Enum and Java Enum
6.Unmarshall From XML using JAXB
7.Set Target Name Space To Be Java Package Name
8.Generate Java Source From XML Schema (XSD)