Jaxb Xml Binding Tutorial - Marshalling Unmarshalling Coffee Object To Xml
XML binding is a concept of generating Java objects from XML together with opposite i.e. XML documents from Java object. Along amongst parsing XML documents using DOM together with SAX parser, XML binding is a fundamental concept to acquire if y'all are working inward a Java application which uses XML inward whatsoever agency e.g. for storing persistence information similar user preferences or for transmitting messages betwixt ii systems etc. XML binding is besides a pop XML Interview question inward Java. JAXB together with XMLBeans are ii mutual ways to reach XML binding inward Java. XML binding, besides known equally XML marshaling together with marshaling has ii sides, starting fourth dimension converting XML document to Java object, alter Java object together with and thence converting dorsum to an XML file. Once y'all bring XML document equally Java object, You tin role the ability of Java programming linguistic communication to procedure together with manipulate the XML elements, attributes etc. In final duet of Java XML tutorials, nosotros bring seen How to parse XML using DOM parser together with How to evaluate XPATH facial expression inward Java.
In this Java XML tutorial nosotros volition verbalize virtually JAXB (Java API for XML Binding) which is an notation based library integrated into Java SDK. Beauty of JAXB is that it doesn't require XML Schema to generate XML documents from Java objects dissimilar XMLBeans together with only rely on POJO(Plain erstwhile Java objects) together with annotations.
In this Java XML tutorial nosotros volition verbalize virtually JAXB (Java API for XML Binding) which is an notation based library integrated into Java SDK. Beauty of JAXB is that it doesn't require XML Schema to generate XML documents from Java objects dissimilar XMLBeans together with only rely on POJO(Plain erstwhile Java objects) together with annotations.
Steps to Create XML from Java using JAXB:
1) Create a POJO together with annotate amongst @XmlRootElement @XmlAccessorType together with annotate all fields amongst @XmlElement. This volition bind Object properties to XML elements
2) Create a JAXBContext
3) Create a Marsaller object together with telephone phone marshal() method on that. While marshaling y'all tin overstep either java.io.Writer, java.io.File or java.io.OutputStream to redirect the generated XML documents.
Benefits of Using JAXB for XML binding inward Java:

1) JAXB is available inward JDK thence it doesn't require whatsoever external library or dependency in Classpath.
2) JAXB doesn't require XML schema to work. Though y'all tin role XML Schema for generating corresponding Java classes together with its pretty useful if y'all bring large together with complex XML Schema which volition number inward huge number of classes but for uncomplicated usage y'all tin precisely annotate your object amongst relevant XML annotations provided past times JAXB bundle i.e. java.xml.binding together with y'all are proficient to go.
3) JAXB is pretty slowly to empathize together with operate. Just await at the below instance of generationg an XML file cast Java flat , what it requires is duet of annotations similar @XmlRootElement together with @XmlAccessorType along amongst 4 lines of code.
4) Modifying XML files inward Java is much easier using JAXB equally compared to other XML parsers similar DOM together with SAX because y'all only bargain amongst POJOs
5) JAXB is to a greater extent than retentiveness efficient than DOM or SAX parser.
How to bind XML document to Java object using JAXB
In this department nosotros volition come across consummate code instance of how to generate XML documents from Java object starting fourth dimension together with than converting XML documents to Java object using JAXB API. In this instance nosotros bring used a uncomplicated Booking flat which stand upwardly for booking data. Following is the sample XML document which volition hold upwardly generate inward this JAXB instance of marshaling together with unmarshaling XML documents.
<booking>
<name>Rohit</name>
<contact>90527869</contact>
<start-date>11-09-2012</start-date>
<end-date>14-02-2012</end-date>
<address>Mumbai</address>
</booking>
<name>Rohit</name>
<contact>90527869</contact>
<start-date>11-09-2012</start-date>
<end-date>14-02-2012</end-date>
<address>Mumbai</address>
</booking>
Here is the Java flat which uses JAXB for creating XML document from Java object together with vice-versa.
import java.io.StringReader;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* JAXB instance to generate xml document from Java object besides called xml marshaling
* from Java object or xml binding inward Java.
*
* @author Javin Paul
*/
public class JAXBXmlBindExample {
public static void main(String args[]){
//Creating booking object for marshaling into XML document
Booking booking = new Booking();
booking.setName("Rohit");
booking.setContact(983672431);
DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
Date startDate = null;
Date endDate = null;
try {
startDate = formatter.parse("11/09/2012");
endDate = formatter.parse("14/09/2012");
} catch (ParseException ex) {
Logger.getLogger(JAXBXmlBindExample.class.getName()).log(Level.SEVERE,
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* JAXB instance to generate xml document from Java object besides called xml marshaling
* from Java object or xml binding inward Java.
*
* @author Javin Paul
*/
public class JAXBXmlBindExample {
public static void main(String args[]){
//Creating booking object for marshaling into XML document
Booking booking = new Booking();
booking.setName("Rohit");
booking.setContact(983672431);
DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
Date startDate = null;
Date endDate = null;
try {
startDate = formatter.parse("11/09/2012");
endDate = formatter.parse("14/09/2012");
} catch (ParseException ex) {
Logger.getLogger(JAXBXmlBindExample.class.getName()).log(Level.SEVERE,
null, ex);
}
booking.setStartDate(startDate);
booking.setEndDate(endDate);
booking.setAddress("Mumbai");
JAXBContext jaxbCtx = null;
StringWriter xmlWriter = null;
try {
//XML Binding code using JAXB
jaxbCtx = JAXBContext.newInstance(Booking.class);
xmlWriter = new StringWriter();
jaxbCtx.createMarshaller().marshal(booking, xmlWriter);
System.out.println("XML Marshal instance inward Java");
System.out.println(xmlWriter);
Booking b = (Booking) jaxbCtx.createUnmarshaller().unmarshal(
}
booking.setStartDate(startDate);
booking.setEndDate(endDate);
booking.setAddress("Mumbai");
JAXBContext jaxbCtx = null;
StringWriter xmlWriter = null;
try {
//XML Binding code using JAXB
jaxbCtx = JAXBContext.newInstance(Booking.class);
xmlWriter = new StringWriter();
jaxbCtx.createMarshaller().marshal(booking, xmlWriter);
System.out.println("XML Marshal instance inward Java");
System.out.println(xmlWriter);
Booking b = (Booking) jaxbCtx.createUnmarshaller().unmarshal(
new StringReader(xmlWriter.toString()));
System.out.println("XML Unmarshal instance inward JAva");
System.out.println(b.toString());
} catch (JAXBException ex) {
Logger.getLogger(JAXBXmlBindExample.class.getName()).log(Level.SEVERE,
System.out.println("XML Unmarshal instance inward JAva");
System.out.println(b.toString());
} catch (JAXBException ex) {
Logger.getLogger(JAXBXmlBindExample.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
@XmlRootElement(name="booking")
@XmlAccessorType(XmlAccessType.FIELD)
class Booking{
@XmlElement(name="name")
private String name;
@XmlElement(name="contact")
private int contact;
@XmlElement(name="startDate")
private Date startDate;
@XmlElement(name="endDate")
private Date endDate;
@XmlElement(name="address")
private String address;
public Booking(){}
public Booking(String name, int contact, Date startDate, Date endDate, String address){
this.name = name;
this.contact = contact;
this.startDate = startDate;
this.endDate = endDate;
this.address = address;
}
public String getAddress() { return address; }
public void setAddress(String address) {this.address = address; }
public int getContact() { return contact; }
public void setContact(int contact) {this.contact = contact;}
public Date getEndDate() { return endDate; }
public void setEndDate(Date endDate) { this.endDate = endDate; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Date getStartDate() { return startDate; }
public void setStartDate(Date startDate) { this.startDate = startDate; }
@Override
public String toString() {
return "Booking{" + "name=" + cite + ", contact=" + contact + ", startDate=" + startDate + ", endDate=" + endDate + ", address=" + address + '}';
}
}
Output
XML Marshal instance inward Java
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><booking><name>Rohit</name><contact>983672431</contact><startDate>2012-09-11T00:00:00-04:30</startDate><endDate>2012-09-14T00:00:00-04:30</endDate><address>Mumbai</address></booking>
XML Unmarshal instance inward JAva
Booking{name=Rohit, contact=983672431, startDate=Tue Sep 11 00:00:00 VET 2012, endDate=Fri Sep 14 00:00:00 VET 2012, address=Mumbai}
}
}
}
@XmlRootElement(name="booking")
@XmlAccessorType(XmlAccessType.FIELD)
class Booking{
@XmlElement(name="name")
private String name;
@XmlElement(name="contact")
private int contact;
@XmlElement(name="startDate")
private Date startDate;
@XmlElement(name="endDate")
private Date endDate;
@XmlElement(name="address")
private String address;
public Booking(){}
public Booking(String name, int contact, Date startDate, Date endDate, String address){
this.name = name;
this.contact = contact;
this.startDate = startDate;
this.endDate = endDate;
this.address = address;
}
public String getAddress() { return address; }
public void setAddress(String address) {this.address = address; }
public int getContact() { return contact; }
public void setContact(int contact) {this.contact = contact;}
public Date getEndDate() { return endDate; }
public void setEndDate(Date endDate) { this.endDate = endDate; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Date getStartDate() { return startDate; }
public void setStartDate(Date startDate) { this.startDate = startDate; }
@Override
public String toString() {
return "Booking{" + "name=" + cite + ", contact=" + contact + ", startDate=" + startDate + ", endDate=" + endDate + ", address=" + address + '}';
}
}
Output
XML Marshal instance inward Java
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><booking><name>Rohit</name><contact>983672431</contact><startDate>2012-09-11T00:00:00-04:30</startDate><endDate>2012-09-14T00:00:00-04:30</endDate><address>Mumbai</address></booking>
XML Unmarshal instance inward JAva
Booking{name=Rohit, contact=983672431, startDate=Tue Sep 11 00:00:00 VET 2012, endDate=Fri Sep 14 00:00:00 VET 2012, address=Mumbai}
If y'all looke at this instance carefully, nosotros bring precisely i flat Booking which is annotated amongst JAXB notation together with a Test flat which performs undertaking of XML binding inward Java. In starting fourth dimension section, nosotros bring created a Booking object together with later on converted it into an XML file equally shown inward output. In instant part, nosotros bring used same XML String to exercise Java object together with that Java object is printed inward console.
That’s all on How to exercise XML binding inward Java using JAXB example. Converting XML documents to Java object or marshaling gives y'all immense ability of Java programming linguistic communication to perform whatsoever enrichment, normalization or manipulating XML elements, attributes together with text inward XML documents.
Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services together with REST API amongst Spring Boot
How to read XML file using SAX parser inward Java
Komentar
Posting Komentar