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

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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;
    }
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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();
        }
    }
}

chevron_right


Output:

generated StudentRecord.xml File for Student Object.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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>

chevron_right


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:



My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.