Skip to main content

Command Palette

Search for a command to run...

How to use these JAXB annotations to marshall an employee object to XML?

Updated
1 min read
How to use these JAXB annotations to marshall an employee object to XML?
S

I love learning about technology and sharing that with others

How to use these JAXB annotations to marshall an employee object to XML?

  1. What is @XmlRootElement and @XmlElement
  2. We have a model , and we want it to be marshalled : menas serialized into a xml that time I can use @XmlRootElement on the Model
  3. below example will marshall the model into a xml file
import javax.xml.bind.*;

public class Demo {

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

        Address address = new Address();
        address.setStreet("1 A Street");

        Employee employee = new Employee();
        employee.setEmployeeId(123);
        employee.setAddress(address);

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

}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <address>
        <street>1 A Street</street>
    </address>
    <employeeId>123</employeeId>
</employee>

POJO

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {

    private Address address;
    private int employeeId;

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

}

Address

There is nothing special that you need to do to have Address marshalled as part of Employee.

public class Address {

    private String street;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

}
4 views

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)