XML binding is a concept of generating Java objects from XML and opposite i.e. XML documents from Java object. Along
with parsing XML documents using DOM
and SAX parser, XML binding is a key concept to learn if you are working in
a Java application which uses XML in any way e.g. for storing persistence data
like user preferences or for transmitting messages between two system etc. XML
binding is also a popular XML
Interview question in Java. JAXB and XMLBeans are two
common ways to achieve XML binding in Java.
XML binding, also known as XML marshaling and marshaling has two
sides, first converting XML document to Java object, modify Java object and than
converting back to XML file. Once you have XML document as Java object, You can
use power of Java programming language to process and manipulate the XML
elements, attributes etc. In last couple of Java XML tutorials we have seen How
to parse XML using DOM parser and How
to evaluate XPATH expression in Java. In this Java XML tutorial we will
talk about JAXB (Java API for XML Binding) which is
an annotation based library integrated into Java SDK. Beauty of JAXB is that
it doesn't require XML Schema to generate XML documents from Java objects
unlike XMLBeans and simply rely on POJO(Plain old Java objects) and annotations.
Steps
to Create XML from Java using JAXB:
1) Create a POJO and annotate with @XmlRootElement @XmlAccessorType and
annotate all fields with @XmlElement. This will bind Object properties
to XML elements
2) Create a JAXBContext
3) Create a Marsaller object and call marshal() method on
that. While marshaling you can pass either java.io.Writer, java.io.File or java.io.OutputStream to
redirect the generated XML documents.
Benefits
of Using JAXB for XML binding in Java:
Though there are couple of options available to bind XML document as Java
object including popular Apache XMLBeans library, JAXB has some advantage. Following
are some of the benefits of using JAXB for XML
binding in Java :
1) JAXB is available in JDK so it doesn't require any external library or
dependency in Classpath.
2) JAXB doesn't require XML schema to work. Though you can use XML Schema
for generating corresponding Java classes and its pretty useful if you have
large and complex XML Schema which will result in huge number of classes but
for simple usage you can just annotate your object with relevant XML annotations
provided by JAXB package i.e. java.xml.binding and you
are good to go.
3) JAXB is pretty easy to understand and operate. Just look at the below
example of generationg an XML file form Java class , what it requires is couple
of annotations like @XmlRootElement and @XmlAccessorType along with
four lines of code.
4) Modifying
XML files in Java is much easier using JAXB as compared to other XML
parsers like DOM
and SAX because you only deal with POJOs
5) JAXB is more memory efficient than DOM or SAX parser.
How to bind XML document to Java object using JAXB
In this section we will see complete code example of how to generate XML
documents from Java object first and than converting XML documents to Java
object using JAXB API. In this example we have used a simple Booking class
which represent booking data. Following is the sample XML document which will
be generate in this JAXB example of marshaling and unmarshaling XML documents.
Mumbai
Here is the Java class which uses JAXB for creating XML document from
Java object and 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 example to generate xml document from Java object also called xml
marshaling
* from Java object or xml binding in 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
example in Java");
System.out.println(xmlWriter);
Booking b = (Booking) jaxbCtx.createUnmarshaller().unmarshal(
new StringReader(xmlWriter.toString()));
System.out.println("XML Unmarshal
example in 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="
+ name + ", contact=" + contact + ", startDate=" + startDate + ", endDate=" + endDate + ", address=" + address + '}';
}
}
Output
XML Marshal example in Java
version="1.0" encoding="UTF-8" standalone="yes"?>
XML Unmarshal example in 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 looke at this example carefully, we have just one class Booking which is
annotated with JAXB annotation and a Test class which performs job of XML
binding in Java. In first section, we have created a Booking object and
later converted it into an XML file as shown in output. In second part, we have
used same XML String to create Java object and that Java object is printed in
console.
That’s all on How to do XML binding in Java using JAXB example.
Converting XML documents to Java object or marshaling gives you immense power of Java
programming language to perform any enrichment, normalization or manipulating
XML elements, attributes and text in XML documents.
Related Java and XML tutorials from Javarevisited blog
Tidak ada komentar:
Posting Komentar