Welcome to JAXB Example Tutorial. Java Architecture for XML Binding (JAXB) provides API for converting Object to XML and XML to Object easily. JAXB was developed as a separate project but it was used widely and finally became part of JDK in Java 6.
Table of Contents
JAXB Tutorial
This tutorial is based on Java 7 and current JAXB version 2.0.
JAXB Marshalling: Converting a Java Object to XML.
JAXB Unmarhsalling: Converting XML to Java Object.
Using JAXB is very easy and it uses java annotations. We need to annotate Java Object to provide instructions for XML creation and then we have to create Marshaller
to convert Object to XML.
Unmarshaller
is used to convert XML to java Object.
JAXBContext
is the entry point for JAXB and provides methods to get marshaller and unmarshaller object.
Some basic and useful JAXB annotations are:
- @XmlRootElement: This is a must have annotation for the Object to be used in JAXB. It defines the root element for the XML content.
- @XmlType: It maps the class to the XML schema type. We can use it for ordering the elements in the XML.
- @XmlTransient: This will make sure that the Object property is not written to the XML.
- @XmlAttribute: This will create the Object property as attribute.
- @XmlElement(name = “abc”): This will create the element with name “abc”
There are some other JAXB annotation that you can learn from JAXB Official Site.
JAXB Example
Let’s run a simple JAXB example program to demonstrate the use of JAXB marshalling and unmarshalling.
package com.journaldev.xml.jaxb;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "Emp")
@XmlType(propOrder = {"name", "age", "role", "gender"})
public class Employee {
private int id;
private String gender;
private int age;
private String name;
private String role;
private String password;
@XmlTransient
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name = "gen")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "ID = " + id + " NAME=" + name + " AGE=" + age + " GENDER=" + gender + " ROLE=" +
role + " PASSWORD=" + password;
}
}
Employee is a normal java bean with private fields and their getters and setters. Notice the use of JAXB annotations to define root element, element name, elements order and transient property.
Here is a test JAXB example program showing JAXB Marshalling and JAXB Unmarshalling.
package com.journaldev.xml.jaxb;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class JAXBExample {
private static final String FILE_NAME = "jaxb-emp.xml";
public static void main(String[] args) {
Employee emp = new Employee();
emp.setId(1);
emp.setAge(25);
emp.setName("Pankaj");
emp.setGender("Male");
emp.setRole("Developer");
emp.setPassword("sensitive");
jaxbObjectToXML(emp);
Employee empFromFile = jaxbXMLToObject();
System.out.println(empFromFile.toString());
}
private static Employee jaxbXMLToObject() {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller un = context.createUnmarshaller();
Employee emp = (Employee) un.unmarshal(new File(FILE_NAME));
return emp;
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
private static void jaxbObjectToXML(Employee emp) {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller m = context.createMarshaller();
//for pretty-print XML in JAXB
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write to System.out for debugging
// m.marshal(emp, System.out);
// Write to File
m.marshal(emp, new File(FILE_NAME));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Above program creates following jaxb-emp.xml file.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp id="1">
<name>Pankaj</name>
<age>25</age>
<role>Developer</role>
<gen>Male</gen>
</Emp>
Check that XML file don’t have password field and we get following output when same XML file is unmarshalled to Object.
ID = 1 NAME=Pankaj AGE=25 GENDER=Male ROLE=Developer PASSWORD=null
That’s all for JAXB example tutorial, as you can see that it’s very easy to use.
what if we want to save multiple objects into a single XML files
I am setting the values using constructor if like below :–
Person p1 = new Person(“hitesh”, “kk”, 24,1056);
Person p2 = new Person(“huhf”,”kjfs”,25,1026);
As per above 2 objects I want to save both the objects into a single file I am using like below code but it is giving me complitaion error
Can you please provide me any solution??
marshaller.marshal(p1,p2,new File(“./src/person.xml”));
Hi,
How can I set xml attribute like
We are using XJC to convert XML to POJO Classes. We are looking into options where some Objects can be made Transient. Is there a way in XJC where we can automatically make some ObjectProperty Transient ?
For Example want to make the field Password Transient when using XJC to convert XSD to Java Object is there any annotations we can use in the bindings to xml that will help with this,
@XMLTransient
private String password;
Your comment is awaiting moderation.
How to distinguish the value by different variable type?
Using your example:
<name>”Pankaj”</name>
<age>25</age>
<role>”Developer”</role>
<gen>”1″</gen>
How to generate soap request by using webservices pls give me a simple example.
use SoapUI
How to generate orm file using jaxb . THe orm file must be of this format
how to use java object in javascript?
You can’t use java object in Javascript. You will have to convert it to XML or JSON and then send it to browser response. Then JS code can work on it.
Nice explanation.
Maybe you can help with that problem…
What do I need to do if I don’t want JAXB to generate empty tags if the Java Object contains an Empty String?
Example: String name = “”;
don’t generate , just generate nothing.
Thanks!!
See if marshal event callback works? Try with below method in your root object (@XmlRootElement annotated) and see how it goes.
Hi Pankaj,
I have a requirement like I want to read the parent and child from the xml file like for ex:
aaa
30
what if the xml I am getting is in a nested format like this :
Pankaj
25
Developer
Male
king street
SF
USA
How will i use the @XmlElement(name = “city”) over getCity() in the java object?
I want to ask, can we convert XML into JAVA object dynamically. I don’t have XSD of that XML. POJO class should auto generate and XML data should accessible by JAVA object.
Is it possible?
If you have XSD, you can use XJC to generate POJO classes. With only XML, it’s not possible because there is no contract that can be established. So you will have to write POJO classes manually in this case.
excellent tutorial. great work by Pankaj as usual.
Thanks Tayab.
Excellent one ….
Good Explanation.
Very nice, and helpful. Thanks.
I am using Soap web service with log4j integrated with spring
my problem is i want to skip password field to print in log file when its print all soap respose request xml in log file
In some cases you have to deal with Java class which is not owned by you, and you can’t put jaxb annotations on the property, in that case Xstream api could be helpful. you can refer Xstream home page https://xstream.codehaus.org/ for more detail. There is a basic tutorial on Xstream at converting java object to xml you can refer that too.
how to convert bpel file into java
Pankaj,
How to convert Java Object inside of an object to XML?
I mean instead of having “primitives” in an object , how object in an object gets marshalled to XML?
Many thanks!
JAXB takes care of that automatically.
Could you help me i wanna transform XML to HTML and i am lose i don’t know how i began
Please provide the xml to convert to java object complete code as early as possible
sir can you help me for this kind of xml to convert to java object complete code as early as possible
lohith
raj
25
Developer
Male