Java HTML / XML How to - Create XML file using java and JAXB








Question

We would like to know how to create XML file using java and JAXB.

Answer

/*www . j  a  v a  2 s  .  co m*/
import java.io.File;

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

@XmlRootElement
public class Main {
  String name;
  int age;
  int id;

  public String getName() {
    return name;
  }

  @XmlElement
  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  @XmlElement
  public void setAge(int age) {
    this.age = age;
  }

  public int getId() {
    return id;
  }

  @XmlAttribute
  public void setId(int id) {
    this.id = id;
  }

  public static void main(String[] args) throws Exception {
    Main customer = new Main();
    customer.setId(100);
    customer.setName("java2s.com");
    customer.setAge(29);

    File file = new File("file.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Main.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(customer, file);
    jaxbMarshaller.marshal(customer, System.out);

  }
}