Open In App

Java Architecture for XML Binding ( JAXB ) | Set-1

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Java Architecture for XML Binding (JAXB) defines an API for reading and writing Java objects to and from XML documents. JAXB gives Java developers an efficient and standard way of mapping between XML and Java code. JAXB makes it easier for developers to extend their applications with XML and Web Services technologies.At First JAXB was developed as a separate project but it was finally became part of JDK in Java 6.

Java Architecture for XML Binding Functions

Application of JAXB

JAXB framework is helpful to perform the following operations:

  • Change XML content into a Java representation.
  • Access and update the Java representation
  • Change the Java representation into XML content.

JAXB Annotations

JAXB uses annotations to indicate the central elements. Some Basics JAXB Annotations which can be used in your java class for JAXB operations are:

Annotation Description
@XmlRootElement Must require annotation for the Object to be used in JAXB. It defines the root element for the XML content.
@XmlType It maps the class to the XML schema type. This is optional. We use @XmlType (propOrder = {“list of attributes in order”}) annotation to define Specific order of elements in XML file.
@XmlTransient To exclude a object from being mapped as part of the inheritance hierarchy you simply need to annotate it with @XmlTransient.
@XmlAttribute This will create the Object property as attribute.
@XmlElement It is used to define element in XML file.You can use @XmlElement(name = “Age”) if you want to give a specific name to that element.

Two Basic Concept related to JAXB are :

  1. Marshalling : Convert a java Object to xml
  2. UnMarshalling : Convert xml to java object

Marshalling

Below is the step by step algorithm for converting Java Objects to XML(Marshalling):

  1. First Create Java Objects to be Marshalled.
  2. Create JAXBContext Object and initializing Marshaller Object.
  3. To get the formatted xml output one can set JAXB_FORMATTTED_OUTPUT to True(this Step is optional).
  4. Create xml file object by providing location of file as parameter to File Class
  5. Call marshal method on Marshaller Object and pass created XML File object to marshal method.
  6. Now the XMl file is created.

Example: First let’s Create a Student object with FullName, StudentDegree, StudentMarks attributes then we are going to convert this object to XML Schema by following above steps.

Creating Student.java class with FullName, StudentDegree, StudentMarks attributes.




import java.util.ArrayList;
  
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
  
// Below annotation defines root element of XML file
@XmlRootElement
public class Student {
  
    private String FullName;
    private String StudentDegree;
    private String StudentMarks;
    public String getFullName()
    {
        return FullName;
    }
    // Sets element of xml with element name is "Student Name"
    @XmlElement(name = "Student Name")
    public void setFullName(String fullName)
    {
        FullName = fullName;
    }
    public String getStudentDegree()
    {
        return StudentDegree;
    }
    @XmlElement(name = "Student Degree")
    public void setStudentDegree(String studentDegree)
    {
        StudentDegree = studentDegree;
    }
    public String getStudentMarks()
    {
        return StudentMarks;
    }
    @XmlElement(name = "Student Marks")
    public void setStudentMarks(String studentMarks)
    {
        StudentMarks = studentMarks;
    }
}


Main Class : JAVAObjToXml.java which is going to convert Student object to XML Schema.




import java.io.File;
import java.util.ArrayList;
  
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
  
public class JAVAObjToXml {
    public static void main(String[] args)
    {
  
        // creating Student object
        Student student = new Student();
        student.setFullName("Aman Singh");
        student.setStudentDegree("Degree");
        student.setStudentMarks("688/900");
  
        try {
  
            // Create JAXB context and initializing Marshaller
            JAXBContext context = JAXBContext.newInstance(Student.class);
            Marshaller marshaller = context.createMarshaller();
  
            // For formatted output of xml
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  
            // Create xml file object
            File XMLfile = new File("D:\\StudentRecord.xml");
  
            // Java object to XML file
            marshaller.marshal(student, XMLfile);
            // Print to console
            marshaller.marshal(student, System.out);
        }
        catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}


Output:

generated StudentRecord.xml File for Student Object.




<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
    <Student Name>Aman Singh</Student Name>
    <Student Degree>Degree</Student Degree>
    <Student Marks>688/900</Student Marks>
</student>


Pros and Cons of Using JAXB

Pros:

  • Easy to marshal XML file to other data targets like inputStream, DOM node.
  • Easy to unmarshal XML file from other data targets.
  • No need to be aware of XML parsing techniques.
  • simple to use than DOM or SAX parser

Cons:

  • JAXB is high layer API so it has less control on parsing than SAX or DOM.
  • It is slower than SAX.

References:



Last Updated : 02 Aug, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads