XML > JAXB > Serialize data to XML Document
Serialize data to XML Document
The following example shows serializing a POJO to an XML document.
The POJO should have a no-arg default constructor and
@XmlRootElement annotation at class level.
package com.bethecoder.tutorials.jaxb.common;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Student {
private String firstName;
private String lastName;
private int age;
private String hobby;
private Date dob;
/**
* NOTE : Should have a no-arg default constructor.
*/
public Student () {
}
public Student ( String firstName, String lastName, int age, String hobby,
Date dob ) {
super () ;
this .firstName = firstName;
this .lastName = lastName;
this .age = age;
this .hobby = hobby;
this .dob = dob;
}
public String getFirstName () {
return firstName;
}
public void setFirstName ( String firstName ) {
this .firstName = firstName;
}
public String getLastName () {
return lastName;
}
public void setLastName ( String lastName ) {
this .lastName = lastName;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public Date getDob () {
return dob;
}
public void setDob ( Date dob ) {
this .dob = dob;
}
}
package com.bethecoder.tutorials.jaxb.tests;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.bethecoder.tutorials.jaxb.common.Student;
public class ToXMLDOM {
public static void main ( String [] args ) throws JAXBException, ParserConfigurationException {
Student student = new Student ( "Sriram" , "Kasireddi" , 2 , "Painting" , new Date ()) ;
/**
* Create DOM
*/
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance () ;
dbf.setNamespaceAware ( true ) ;
Document doc = dbf.newDocumentBuilder () .newDocument () ;
/**
* Create JAXB Context from the classes to be serialized
*/
JAXBContext context = JAXBContext.newInstance ( Student. class ) ;
Marshaller m = context.createMarshaller () ;
m.setProperty ( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ) ;
m.marshal ( student, doc ) ;
System.out.println ( "Student Node : " + doc.getFirstChild ()) ;
NodeList nodelist = doc.getFirstChild () .getChildNodes () ;
Node child = null ;
for ( int i = 0 ; i < nodelist.getLength () ; i ++ ) {
child = nodelist.item ( i ) ;
System.out.println ( "|_" + child.getNodeName () + " : " + child.getTextContent ()) ;
}
}
}
It gives the following output,
Student Node : [student: null]
|_age : 2
|_dob : 2011-09-25T14:51:20.156+05:30
|_firstName : Sriram
|_hobby : Painting
|_lastName : Kasireddi