JAXB: Marshalling and Unmarshalling in java

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Hello all, In this part of tutorial we are going to see what is marshalling and unmarshalling and how we can write the state of an object into xml files. We have used serialization to write object state into a file in the previous post. In this, we will learn how to write data into xml files.

Introduction:

JAXB is Java Architecture for Xml Binding. We can represent java objects into xml and xml into java object using JAXB which involves two concepts

  • Marshalling: Conversion of java object into xml form.
  • Unmarshaling: Conversion of xml into java object.

 

Consider we have a class Bike as follows.

What do the annotations provided in the class mean?

  1. @XmlRootElement(name = "bike"):  This class is the root element of xml file we are going to create and the name of root element is bike .
  2. @XmlAttribute  : This means  the field will be used as an attribute in the xml file.
  3. @XmlElement : The field will be used as element of the tag.

Marshalling

  1. Create a JAXBContext for Bike class using JAXBContext context = JAXBContext.newInstance(Bike.class);.
  2. Create a Marshaller from context using Marshaller jaxbMarshaller = context.createMarshaller();
  3. Use jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); so that the generated xml is formatted and easy to read.
  4. Finally marshal the Bike   using  jaxbMarshaller.marshal(hondaCBR, bikeDump);  where bikeDump is the file object created using File bikeDump = new File("./bikeDump.xml");

 

Unmarshalling

  1. Create Unmarshaller from the context created previously using Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();
  2. Unmarshal the xml file into Bike object using Bike unMarshalledBike = (Bike) jaxbUnmarshaller.unmarshal(bikeDump);

So we will write a JAXBTest class to try it out as follows

Run this program and you will see the file is generated in the same directory as your eclipse project

After marshalling is done, this file is again read and converted into java object using Bike unMarshalledBike = (Bike) jaxbUnmarshaller.unmarshal(bikeDump); which prints the object as follows

This means unmarshalling is successful.

In the next part of this tutorial series, we will learn how to deal with collections while using JAXB.

 

 

 

Share Button

3 comments for “JAXB: Marshalling and Unmarshalling in java

  1. Pranaya
    June 27, 2016 at 2:15 am

    Could please give hint about difference between attributes and elements in XML

    • Pranaya
      June 27, 2016 at 2:18 am

      Sample copy of XML

Leave a Reply

Your email address will not be published. Required fields are marked *