Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

About JAXB (Java Architecture for XML Binding)

DZone's Guide to

About JAXB (Java Architecture for XML Binding)

JAXB is used to convert XML to Java objects and Java objects to XML. It's an API that gives us the power to read and write Java Objects to and from XML documents.

· Integration Zone
Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

JAXB stands for Java Architecture for XML Binding. It is used to convert XML to Java objects and Java objects to XML. JAXB is an API that  gives us the power to read and write Java Objects to and from XML documents.

Please see below the pictorial representation of the above statement.

http://3.bp.blogspot.com/-hA6JNvBemn8/Uk7dYktCNpI/AAAAAAAAAnY/fvzgotyrnf4/s1600/image.JPG

This API is used when we are supposed to read the XML document and populate the same to Java objects and vice-versa.

JAXB provides two methods to achieve their goal:

  • Marshalling: simply used for the conversion of a Java object to XML

  • UnMarshalling: simply used for the conversion of an XML document to Java object.

Let us understand the same using a Java program as below:

CD.java

package arun.jaxb.test;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "cd")
// we are defining the order in which the fields are written
@XmlType(propOrder = {"albumName", "albumArtist", "publisher", "composer"})
public class CD {

      private String albumName;
      private String albumArtist;
      private String publisher;
      private String composer;

      @XmlElement(name = "albumName")
      public String getAlbumName() {
            return albumName;
      }

      public void setAlbumName(String albumName) {
            this.albumName = albumName;
      }

      public String getAlbumArtist() {
            return albumArtist;
      }

      public void setAlbumArtist(String albumArtist) {
            this.albumArtist = albumArtist;
      }

      public String getPublisher() {
            return publisher;
      }

      public void setPublisher(String publisher) {
            this.publisher = publisher;
      }

      public String getComposer() {
            return composer;
      }

      public void setComposer(String composer) {
            this.composer = composer;
      }
}

CDStore.java

package arun.jaxb.test;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

//This statement means that class "CDstore.java" is the root-element of our example
@XmlRootElement(namespace = "arun.jaxb.test")
public class CDStore {

  // XmLElementWrapper generates a wrapper element around XML representation
  @XmlElementWrapper(name = "cdList")

  // XmlElement sets the name of the entities
  @XmlElement(name = "cd")
  private ArrayList<CD> cdList;
  private String name;
  private String location;

  public void setBookList(ArrayList<CD> cdList) {
    this.cdList = cdList;
  }

  public ArrayList<CD> getCDList() {
    return cdList;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getLocation() {
    return location;
  }

  public void setLocation(String location) {
    this.location = location;
  }
}

CDMain.java

package arun.jaxb.test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class CDMain {
      private static final String CD_STORE_XML = "./cd-store.xml";

      public static void main(String ... args) throws JAXBException, IOException {

            ArrayList<CD> cdList = new ArrayList<CD>();

            CD cd_1 = new CD();
            cd_1.setAlbumName("X-Men: Apocalypse");
            cd_1.setPublisher("20th Century Fox");
            cd_1.setAlbumArtist("James McAvoy - Jennifer Lawrence");
            cd_1.setComposer("John Ottman");
            cdList.add(cd_1);

            CD cd_2 = new CD();
            cd_2.setAlbumName("Captain America: Civil War");
            cd_2.setPublisher("Marvel Studios");
            cd_2.setAlbumArtist("Chris Evans - Scarlett Johansson");
            cd_2.setComposer("Henry Jackman");
            cdList.add(cd_2);

            CD cd_3 = new CD();
            cd_3.setAlbumName("Sholay");
            cd_3.setPublisher("Sippy Films");
            cd_3.setAlbumArtist("Amitabh Bachchan - Dharmendra");
            cd_3.setComposer("R. D. Burman");
            cdList.add(cd_3);

            CDStore cdStore = new CDStore();
            cdStore.setName("Planet M Store");
            cdStore.setLocation("Mumbai");
            cdStore.setBookList(cdList);

            javaObjectToXML(cdStore);
            XMLToJavaObject();
      }

      /**
       * Java Object to XML
       * @param cdStore
       * @throws JAXBException
       */
      private static void javaObjectToXML(CDStore cdStore) throws JAXBException{

            // create JAXB context and instantiate Marshaller
            JAXBContext context = JAXBContext.newInstance(CDStore.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // Write to System.out
            m.marshal(cdStore, System.out);

            // Write to File
            m.marshal(cdStore, new File(CD_STORE_XML));
      }

      /**
       * XML to java Object
       * @throws JAXBException
       */
      private static void XMLToJavaObject() throws JAXBException{

            // create JAXB context and instantiate Unmarshaller
            JAXBContext context = JAXBContext.newInstance(CDStore.class);
            Unmarshaller u = context.createUnmarshaller();
            Object obj = u.unmarshal(new File(CD_STORE_XML));

            if(obj instanceof CDStore) {
                  CDStore cs = (CDStore) obj;
                  System.out.println("============ Printing XML to Java Object way ====================");
                  System.out.println("Store Location : "+cs.getLocation());
                  System.out.println("Store Name : "+cs.getName());                             
                for(CD cd : cs.getCDList()) {
                        System.out.println(cd.getAlbumArtist());
                        System.out.println(cd.getAlbumName());
                        System.out.println(cd.getComposer());
                        System.out.println(cd.getPublisher());
System.out.println("===================================");
                  }
            }
      }
}

The entry point of this program is CDMain.java,so if we will run this main program, first it is creating three CD objects and setting their properties and then adding these CD objects to a list. The CDStore class has its own CD Store name and location that has the CD list as defined above. Now we are converting this CDStore java object to XML documents using Marshalling in javaObjectToXML() method and again from XML to Java Object using UnMarshalling in XMLToJavaObject() method.

See the output as below.

XML document is as below from Java object:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:cdStore xmlns:ns2="arun.jaxb.test">
    <cdList>
        <cd>
            <albumName>X-Men: Apocalypse</albumName>
            <albumArtist>James McAvoy - Jennifer Lawrence</albumArtist>
            <publisher>20th Century Fox</publisher>
            <composer>John Ottman</composer>
        </cd>
        <cd>
            <albumName>Captain America: Civil War</albumName>
            <albumArtist>Chris Evans - Scarlett Johansson</albumArtist>
            <publisher>Marvel Studios</publisher>
            <composer>Henry Jackman</composer>
        </cd>
        <cd>
            <albumName>Sholay</albumName>
            <albumArtist>Amitabh Bachchan - Dharmendra</albumArtist>
            <publisher>Sippy Films</publisher>
            <composer>R. D. Burman</composer>
        </cd>
    </cdList>
    <location>Mumbai</location>
    <name>Planet M Store</name>
</ns2:cdStore>

Java object properties are printed after conversion from XML as below:

Store Location : Mumbai
Store Name : Planet M Store
James McAvoy - Jennifer Lawrence
X-Men: Apocalypse
John Ottman
20th Century Fox
===================================================
Chris Evans - Scarlett Johansson
Captain America: Civil War
Henry Jackman
Marvel Studios
===================================================
Amitabh Bachchan - Dharmendra
Sholay
R. D. Burman
Sippy Films
===================================================

Hopefully, this gives you a clear understanding of JAXB.

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:
java ,jaxb ,integration ,xml

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}