Marshal Java object to xml and output to console : JAXB « JDK 6 « Java

Marshal Java object to xml and output to console



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, System.out);


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;
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


Related examples in the same category

1.simple jaxb
2.Marshal Java object to a file
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)