Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

    public static void main(String[] args) throws Exception {
        Company company = new Company();

        Employee employee1 = new Employee();
        employee1.setId("1");
        employee1.setName("Jane Doe");
        company.getEmployees().add(employee1);

        Employee employee2 = new Employee();
        employee2.setId("2");
        employee2.setName("John Smith");
        employee2.setManager(employee1);
        employee1.getReports().add(employee2);
        company.getEmployees().add(employee2);

        Employee employee3 = new Employee();
        employee3.setId("3");
        employee3.setName("Anne Jones");
        employee3.setManager(employee1);
        employee1.getReports().add(employee3);
        company.getEmployees().add(employee3);

        JAXBContext jc = JAXBContext.newInstance(Company.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(company, System.out);
    }

}

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Company {

    @XmlElement(name = "employee")
    private List<Employee> employees;

    public Company() {
        employees = new ArrayList<Employee>();
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }

}

@XmlAccessorType(XmlAccessType.FIELD)
class Employee {

    @XmlAttribute
    @XmlID
    private String id;

    @XmlAttribute
    private String name;

    @XmlIDREF
    private Employee manager;

    @XmlIDREF
    @XmlList
    private List<Employee> reports;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Employee getManager() {
        return manager;
    }

    public void setManager(Employee manager) {
        this.manager = manager;
    }

    public List<Employee> getReports() {
        return reports;
    }

    public void setReports(List<Employee> reports) {
        this.reports = reports;
    }

    public Employee() {
        reports = new ArrayList<Employee>();
    }

}