Unmarshalling the Marshalled: XML BINDING IN JAVA
Tags: java, jaxb, xml
Published: 2019-08-14 20:29:52

During my first software engineering internship, I was tasked to build a USSD application. Since USSD applications are unstructured, the design of the application is specified by the Telecommunication company the application is being built for. The API from the Telecommunication company specified that the data would be transmitted as XML (Extensible Markup Language). Hence my first challenge was figuring out how to convert the XML to Java Objects to be able to manipulate it and add logic to it in my code.
   
![USSD APPLICATION SCHEMA](https://i.pinimg.com/originals/66/80/db/6680db61a9dcad820393a709d542b1f1.png)
                                                                                            There are various java APIs for XML Binding; Simple API for XML(SAX), Document Object Model (DOM), JiBx and Java Architecture for XML Binding (JAXB).

#Simple API for XML(SAX)
It is event driven parser for XML files. It reads the XML sequentially from top to bottom and sends notifications to the application, an element and attribute at a time until the root element is closed using callbacks. SAX is normally used when the XML document is to be processed linearly and sequentially. Since, it only processes XML files in this manner, components of the XML cannot be accessed randomly, and you need to write your own code to manipulate or keep track of the parsed data. Read more about SAX [here](https://docs.oracle.com/javase/tutorial/jaxp/sax/index.html)

# Document Object Model (DOM)
It allows an application to easily access and change the style, structure and contents of an XML file. It mostly used when the information in XML is to be used multiple times. Parsing an XML file using DOM returns a tree structure with the different elements of the XML, so it’s great for manipulating document structure. Luckily, DOM has several functions available that can be used to play around with the contents and structure of the document. Read more about DOM [here](https://www.oracle.com/technetwork/java/dom-139036.html)

#JiBX
According to various sources, JiBX is faster compared to JAXB and the likes. JiBX is also used for XML binding but unlike JAXB which focuses on generating code, JiBX focuses on mapping data. It uses Binding definition documents to determine how XML should be converted to Java Objects and vice versa.
Read more about JiBX [here](http://jibx.sourceforge.net/)

# Java Architecture for XML Binding (JAXB)
JAXB is a very popular API in web services. Many people argue that it is the standard API among the two APIs discussed above. JAXB comes with Java 1.6, Java versions lower than that would need the JAXB jar file which can be found [here](https://drive.google.com/open?id=1lxs6I8Kg_L3u-EHNbS53Y_lhKLnKllpa). I quite agree because unlike SAX and DOM that are lower level APIs that just parse the XML documents, JAXB converts the XML elements and attributes to a Java Object and vice versa. This bring me to my main point. JAXB has two useful methods; One is used for Marshalling Java Objects to XML and the other is for Unmarshalling the XML back to Java Objects.

# HOW DID IT GET MARSHALLED??
Basically, converting Java Objects to XML is called Marshalling. In order to Marshall XML, there must be a POJO (Plain Old Java Object). This Java Object provides a schema for the XML to be formed. The name of the POJO class becomes the root element of the XML. JAXB indicates elements of the XML using annotations. 

*@XmlRootElement(name=”namespace”)* – This is used to define the root element of the XML. It is used at the top-level class. The name attribute is optional. The default root element which is used is the class name of the POJO.

*@XmlAttribute* – This is used to define the attributes of the root element.

*@XmlElement* – This is used to define the properties the POJO class that would later be sub-elements of the root element in the XML tree after marshalling.

#### Code for POJO
```
package com.jaxb;

//import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 


@XmlRootElement(name="USSDMenuRequest")
public class USSDMenuRequest{
		
	
	private  String sessionId;
	private  String messageid;
	private  String shortCode;
	private   String prompt;
	private   String timeStamp;
	  



  
	@XmlElement(name="sessionId")
	public void setSessionId(String sessionId){
		this.sessionId = sessionId;
	}

	 public String getSessionId(){
	    return sessionId;
	 }


  public String getMessageid(){
     return messageid;
}

  	@XmlElement(name="messageid")
  	public void setMessageid(String messageid){
  		this.messageid = messageid;
}
  	
	@XmlElement(name="shortCode")
	public void setShortCode(String shortCode){
		this.shortCode = shortCode;
}

	public String getShortCode(){
	   return shortCode;
	}
	
  	
	@XmlElement(name="prompt")
	public void setPrompt(String prompt){
		this.prompt = prompt;
}

	public String getKeyWord(){
	   return keyWord;
}

   public String getTimeStamp(){
      return timeStamp;
   }


	}
```

The properties of the POJO class have getter and setter methods. The getter method is used to access the value passed to XML sub-element whilst the setter methods are used to change the existing values of the XML sub-elements. In the POJO above, USSDDynMenuRequest will be the root element of the XML tree with messageid, sessionId etc as sub-elements.



#### Code for Marshalling

```
-------------------------- MARSHALLING XML  ----------------------------------
  public static void marshalXML() {
	try {		
			
	System.out.println("Marshalling Java Object to XML-------");
			
	//creating the JAXB context
        JAXBContext jContext = JAXBContext.newInstance(USSDMenuRequest.class); 
		    
	//create the marshaller object
        Marshaller marshallerObj = jContext.createMarshaller();
		    

        //the XML should be properly indented and formatted
	marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		   
	USSDDynMenuRequest Sendrequest= new USSDMenuRequest();
		    
        Sendrequest.setShortCode("124");
        Sendrequest.setPrompt("Start");
	Sendrequest.setMessageid("0244708099");
	Sendrequest.setSessionId("789888886adh");
	
		    
	//calling the marshall method
	marshallerObj.marshal(Sendrequest, new FileOutputStream("response.xml"));
		}
    catch(Exception e){
		 e.printStackTrace();
			}
		}

```
In the code above, the response.xml file would be created using the schema described in the USSDDynMenuRequest.class . The values of the XML sub-elements would be the same as the ones provided by the setter methods of the respective class properties.


# UNMARSHALLING 
Unmarshalling is the conversion of XML to Java Objects. There are various ways in which this can be done.  The easiest way which involves little or no code is the use of an online resource [here](http://pojo.sodhanalibrary.com). All you have to do is paste our XML content and TA-DA .... you have your POJO. One of the other numerous ways is to use the Unmarshaller object of the JAXBContext class. 

```
//-------------------------- UNMARSHALLING XML  -------------------------------
public static void unmarshalXML(File xmlFile) {
	try {		
	System.out.println("Unmarshalling XML to Java Object-------");
		
	//creating the JAXB context
	JAXBContext jContext = JAXBContext.newInstance(USSDMenuRequest.class); 
	    
	 //create the unmarshal object
	 Unmarshaller unmarshallerObj = jContext.createUnmarshaller();
	    
     //call the unmarshal method
	 USSDMenuRequest request= (USSDMenuRequest) unmarshallerObj.unmarshal(xmlFile);
	    
	request.setStarCode("124");
	request.setKeyWord("Start");
	    
  System.out.println(request.getShortCode() + " " + request.getPrompt() );
	}
	catch(Exception e){
		    e.printStackTrace();
		}
	}
```

Kindly find the complete code [here](https://gist.github.com/Lormenyo/8c019c155ad7176834391131c8a5de78)

*I hope you enjoyed this article. It is very cool. Try it out. Follow me on Twitter at [@blessed_hl](https://twitter.com/blessed_hl?lang=en)*