JAXB Marshalling Example: Converting Object into XML
By the help of Marshaller interface, we can marshal(write) the object into xml document. In the previous page, we have seen the simple example of converting object into xml.
In this example, we are going to convert the object into xml having primitives, strings and collection objects.
Let's see the steps to convert java object into XML document.
- Create POJO or bind the schema and generate the classes
- Create the JAXBContext object
- Create the Marshaller objects
- Create the content tree by using set methods
- Call the marshal method
File: Question.java
File: 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;
}
}
File: ObjectToXml.java
# Output:
The generated xml file will look like this:
File: question.xml
download this example