JAXB. Sounds like a brand name doesn’t it? It stands for Java Architectural XML Binding. Being used to marshal (write) and unmarshal (read) XML documentation, it is simple to code in Java! All one needs is a few imports to get started:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
The Root Element is for the XML document while the Element import is for the Root Element. Attribute annotation specifies root element attribute.
@XmlRootElement
public class Employee {
private int id;
private String name;
public Employee() {}
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
}
The XmlRootElement annotates class data, XmlAttribute annotates Getter and Setter methods, and XmlElement would annotate Getter and Setter methods for each class data element, in this example values id and name.
To marshal an object, two objects must be created: a JAXBContext object using new instance of the root element class, then a marshal object using createMarshaller. Import the following: import javax.xml.bind.JAXBContext, import javax.xml.bind.Marshaller, and java.io.FileOutputStream
JAXBContext contextObj = JAXBContext.newInstance(Employee.class);
Marshaller marshallerObj = contextObj.createMarshaller();
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Employee emp1=new Employee(1,"John Smith");
marshallerObj.marshal(emp1, new FileOutputStream("employee.xml"));
With this code, we can successfully export an XML file containing the data of one Employee!