JAXB tutorial

What is JAXB?

JAXB stands for Java architecture for XML binding.It is used to convert XML to java object and java object to XML.JAXB defines an API for reading and writing Java objects to and from XML documents.Unlike SAX and DOM,we don’t need to be aware of XML parsing techniques.
There are two operations you can perform using JAXB
  1. Marshalling :Converting a java object to XML
  2. UnMarshalling :Converting a XML to java object

JAXB Tutorial

We will create a java program to marshal and unmarshal.

For Marshalling:

JAXB Marshalling

For Unmarshalling:

JAXB unmarshalling

Java program:

With the help of annotations and API provided by JAXB,converting a java object to XML and vice versa become very easy.

1.Country.java

A Java object which will be used to convert to and from XML

Create Country.java  in src->org.arpit.javapostsforlearning.jaxb

@XmlRootElement:This annotation defines root element of XML file. @XmlType(propOrder = {“list of attributes in order”}):This is used to define order of elements in XML file.This is optional. @XmlElement:This is used to define element in XML file.It sets name of entity. @XmlElementWrapper(name = “name to be given to that wrapper”):It generates a wrapper element around XML representation.E.g.In above example, it will generate around each element

2.State.java

 

3.JAXBJavaToXml.java

After running above program,you will get following output

Console output:

Now we will read above generated XML and retrieve country object from it.

4.JAXBXMLToJava.java

After running above program,you will get following output

Console output:

JAXB advantages:

  • It is very simple to use than DOM or SAX parser
  • We can marshal XML file to other data targets like inputStream,URL,DOM node.
  • We can unmarshal XML file from other data targets.
  • We don’t need to be aware of XML parsing techniques.
  • We don’t need to access XML in tree structure always.

JAXB disadvantages:

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

Source code:

Was this post helpful?

Leave a Reply

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