Jaxb Xml Binding Tutorial - Marshalling Unmarshalling Coffee Object To Xml
XML binding is a concept of generating Java objects from XML in addition to opposite i.e. XML documents from Java object. Along amongst parsing XML documents using DOM in addition to SAX parser, XML binding is a fundamental concept to acquire if you lot are working inward a Java application which uses XML inward whatsoever means e.g. for storing persistence information similar user preferences or for transmitting messages betwixt 2 systems etc. XML binding is besides a pop XML Interview question inward Java. JAXB in addition to XMLBeans are 2 mutual ways to laissez passer XML binding inward Java. XML binding, besides known equally XML marshaling in addition to marshaling has 2 sides, start converting XML document to Java object, alteration Java object in addition to and thus converting dorsum to an XML file. Once you lot accept XML document equally Java object, You tin give the sack role the ability of Java programming linguistic communication to procedure in addition to manipulate the XML elements, attributes etc. In final duet of Java XML tutorials, nosotros accept seen How to parse XML using DOM parser in addition to How to evaluate XPATH appear inward Java.
In this Java XML tutorial nosotros volition utter nearly JAXB (Java API for XML Binding) which is an musical note based library integrated into Java SDK. Beauty of JAXB is that it doesn't require XML Schema to generate XML documents from Java objects different XMLBeans in addition to exactly rely on POJO(Plain quondam Java objects) in addition to annotations.
In this Java XML tutorial nosotros volition utter nearly JAXB (Java API for XML Binding) which is an musical note based library integrated into Java SDK. Beauty of JAXB is that it doesn't require XML Schema to generate XML documents from Java objects different XMLBeans in addition to exactly rely on POJO(Plain quondam Java objects) in addition to annotations.
Steps to Create XML from Java using JAXB:
1) Create a POJO in addition to annotate amongst @XmlRootElement @XmlAccessorType in addition to annotate all fields amongst @XmlElement. This volition bind Object properties to XML elements
2) Create a JAXBContext
3) Create a Marsaller object in addition to telephone telephone marshal() method on that. While marshaling you lot tin give the sack top 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:
Though at that topographic point are duet of options available to bind XML document equally Java object including pop Apache XMLBeans library, JAXB has closed to advantage. Following are closed to of the benefits of using JAXB for XML binding inward Java :
1) JAXB is available inward JDK thus it doesn't require whatsoever external library or dependency in Classpath.
2) JAXB doesn't require XML schema to work. Though you lot tin give the sack role XML Schema for generating corresponding Java classes in addition to its pretty useful if you lot accept large in addition to complex XML Schema which volition resultant inward huge publish of classes but for elementary usage you lot tin give the sack exactly annotate your object amongst relevant XML annotations provided past times JAXB bundle i.e. java.xml.binding in addition to you lot are practiced to go.
3) JAXB is pretty slow to sympathise in addition to operate. Just await at the below instance of generationg an XML file cast Java class , what it requires is duet of annotations similar @XmlRootElement in addition to @XmlAccessorType along amongst iv lines of code.
4) Modifying XML files inward Java is much easier using JAXB equally compared to other XML parsers similar DOM in addition to SAX because you lot only bargain amongst POJOs
5) JAXB is to a greater extent than retention efficient than DOM or SAX parser.
How to bind XML document to Java object using JAXB
In this department nosotros volition run into consummate code instance of how to generate XML documents from Java object start in addition to than converting XML documents to Java object using JAXB API. In this instance nosotros accept used a elementary Booking class which stand upwards for booking data. Following is the sample XML document which volition live on generate inward this JAXB instance of marshaling in addition to 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 class which uses JAXB for creating XML document from Java object in addition to 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=" + mention + ", 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=" + mention + ", 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 you lot looke at this instance carefully, nosotros accept exactly i class Booking which is annotated amongst JAXB musical note in addition to a Test class which performs project of XML binding inward Java. In start section, nosotros accept created a Booking object in addition to after converted it into an XML file equally shown inward output. In minute part, nosotros accept used same XML String to do Java object in addition to that Java object is printed inward console.
That’s all on How to do XML binding inward Java using JAXB example. Converting XML documents to Java object or marshaling gives you lot immense ability of Java programming linguistic communication to perform whatsoever enrichment, normalization or manipulating XML elements, attributes in addition to text inward XML documents.
Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services in addition to REST API amongst Spring Boot
How to read XML file using SAX parser inward Java
0 Response to "Jaxb Xml Binding Tutorial - Marshalling Unmarshalling Coffee Object To Xml"
Post a Comment