JAXB (Java Architecture of XML Binding) is a fast and convenient way to convert XML into Java objects, and Java objects to XML. It consists of an API for reading and writing Java objects to and from XML.
You can perform the following two operations using JAXB:
- Marshalling: It means converting Java objects to XML.
- UnMarshalling: It means converting XML to Java objects.
Features of JAXB:
- Annotation support: JAXB supports annotation, so less coding is required. The javax.xml.bind.annotation package consists of classes and interfaces required to develop applications.
- Support all W3C XML Schema features: It supports all the W3C schema features.
- Additional Validation Capabilities: It supports additional validation capabilities supported by JAXP validation API.
- Small Runtime Library: It requires a small runtime library.
- Reduction of generated schema-derived classes: It reduces the usage of several generated schema-derived classes.
Annotations used in JAXB:
Java Annotations are used in JAXB for augmenting the generated classes with additional information, which helps in preparing them for JAXB runtime. The below example will help to understand the annotations easily:
@XmlRootElement(name = "book") @XmlType(propOrder = { "id", "name", "date" }) public class Book { private Long id; private String name; private String author; private Date date; @XmlAttribute public void setId(Long id) { this.id = id; } @XmlElement(name = "title") public void setName(String name) { this.name = name; } @XmlTransient public void setAuthor(String author) { this.author = author; } }
- @XmlRootElement: it contains the name of the root XML element.
- @XmlType: it defines the order in which the fields are written.
- @XmlElement: it defines the actual XML element name.
- @XmlAttribute: it defines the id field that is mapped as an attribute.
- @XmlTransient: it consists of those fields, which we do not want to include in XML.
JAXB Marshalling: It means converting the object into XML. The steps that are used to convert Java objects into XML are:
- Create POJO and generate the classes.
- Create a JAXBContext object.
- Create a Marshaller object.
- Create a content tree by using the set method.
- Call the marshal method.
Question.java
import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Question { private int id; private String questionname; private List<Answer> answers; public Question() {} public Question(int id, String questionname, List<Answer> answers) { super(); this.id = id; this.questionname = questionname; this.answers = answers; } @XmlAttribute public int getId() { return id; } public void setId(int id) { this.id = id; } @XmlElement public String getQuestionname() { return questionname; } public void setQuestionname(String questionname) { this.questionname = questionname; } @XmlElement public List<Answer> getAnswers() { return answers; } public void setAnswers(List<Answer> answers) { this.answers = answers; } }
Answer.java
public class Answer {
private int id;
private String answername;
private String postedby;
public Answer() {}
public Answer(int id, String answername, String postedby) {
super();
this.id = id;
this.answername = answername;
this.postedby = postedby;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAnswername() {
return answername;
}
public void setAnswername(String answername) {
this.answername = answername;
}
public String getPostedby() {
return postedby;
}
public void setPostedby(String postedby) {
this.postedby = postedby;
}
}
ObjectToXml.java
import java.io.FileOutputStream; import java.util.ArrayList; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class ObjectToXml { public static void main(String[] arg) throws Exception{ JAXBContext contextObj = JAXBContext.newInstance(Question.class); Marshaller marshallerObj = contextObj.createMarshaller(); marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Answer ans1=new Answer(101,"java is a programming language","ravi"); Answer ans2=new Answer(102,"java is a platform","john"); ArrayList<Answer> list=new ArrayList<Answer>(); list.add(ans1); list.add(ans2); Question que=new Question(1,"What is java?",list); marshallerObj.marshal(que, new FileOutputStream("question.xml")); } }
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <question id="1"> <answers> <answername>java is a programming language</answername> <id>101</id> <postedby>ravi</postedby> </answers> <answers> <answername>java is a platform</answername> <id>102</id> <postedby>john</postedby> </answers> <questionname>What is java?</questionname> </question>
JAXB Unmarshalling: This means converting the XML into an object. The steps that are used to convert XML into Java object are:
- Create POJO and generate the classes.
- Create a JAXBContext object.
- Create a Marshaller object.
- Call the marshal method.
- Use the getter method to access the data.
Question.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <question id="1"> <answers> <answername>java is a programming language</answername> <id>101</id> <postedby>ravi</postedby> </answers> <answers> <answername>java is a platform</answername> <id>102</id> <postedby>john</postedby> </answers> <questionname>What is java?</questionname> </question>
POJO class: Question.java
import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Question { private int id; private String questionname; private List<Answer> answers; public Question() {} public Question(int id, String questionname, List<Answer> answers) { super(); this.id = id; this.questionname = questionname; this.answers = answers; } @XmlAttribute public int getId() { return id; } public void setId(int id) { this.id = id; } @XmlElement public String getQuestionname() { return questionname; } public void setQuestionname(String questionname) { this.questionname = questionname; } @XmlElement public List<Answer> getAnswers() { return answers; } public void setAnswers(List<Answer> answers) { this.answers = answers; } }
Answer.java
public class Answer {
private int id;
private String answername;
private String postedby;
public Answer() {}
public Answer(int id, String answername, String postedby) {
super();
this.id = id;
this.answername = answername;
this.postedby = postedby;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAnswername() {
return answername;
}
public void setAnswername(String answername) {
this.answername = answername;
}
public String getPostedby() {
return postedby;
}
public void setPostedby(String postedby) {
this.postedby = postedby;
}
}
XmlToObject.java
import java.io.File;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class XmlToObject {
public static void main(String[] args) {
try {
File file = new File("question.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Question.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Question que= (Question) jaxbUnmarshaller.unmarshal(file);
System.out.println(que.getId()+" "+que.getQuestionname());
System.out.println("Answers:");
List<Answer> list=que.getAnswers();
for(Answer ans:list)
System.out.println(ans.getId()+" "+ans.getAnswername()+" "+ans.getPostedby());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Output:
1 What is java?
Answers:
101 java is a programming language ravi
102 java is a platform john
Advantages of JAXB:
- It is simpler than the SAX or DOM parser.
- No need to be aware of XML parsing techniques.
- No need to access XML in a tree structure.
Disadvantages of JAXB:
- Performance Overhead:
- JAXB can introduce performance overhead due to the conversion process between XML and Java objects. Large XML files or complex object models can significantly slow down the application.
- Memory Consumption:
- JAXB tends to consume more memory as it loads the entire XML document into memory when binding it to Java objects. This can be problematic for large XML documents, leading to memory management issues.
- Limited Flexibility in XML Structure:
- JAXB is limited when working with XML structures that do not conform to a fixed schema or have complex, highly nested elements. It works best with well-defined schemas, making it less flexible when dealing with dynamic or loosely defined XML formats.
- Error Handling Complexity:
- JAXB’s error handling can be complex, especially when dealing with XML validation errors. The error messages are often not very descriptive, making it difficult to debug and fix issues during the unmarshalling process.
- Dependency on Annotations:
- JAXB relies heavily on annotations to map Java classes to XML schemas. This can clutter the code, making maintenance difficult, especially when dealing with large object models.
- Limited Support for JSON:
- While JAXB is designed primarily for XML, its JSON support is not as robust or straightforward compared to other libraries specifically designed for JSON processing, like Jackson or GSON.
- Requires XML Schema Definition (XSD):
- JAXB often requires an XML Schema Definition (XSD) to generate Java classes, which adds an extra step to the development process. Managing XSD files can be cumbersome and error-prone.
- Static Binding:
- JAXB uses static binding, meaning that once the Java classes are generated, changes to the XML structure require regeneration of these classes. This can be time-consuming and error-prone in agile development environments where changes are frequent.
- Compatibility Issues with Complex XML Structures:
- JAXB struggles with XML features such as mixed content, namespaces, or advanced schema constructs. Handling such complexities requires additional code and workarounds, which can complicate development.
- Steep Learning Curve:
- For developers unfamiliar with XML binding concepts, JAXB can have a steep learning curve, particularly when dealing with advanced features such as customizing bindings or handling complex XML schemas.
These disadvantages make JAXB suitable primarily for scenarios where XML schemas are stable, and performance or memory constraints are not critical. For more dynamic or large-scale XML processing, alternative approaches may be more efficient.