Step by step Example of JAXB 2.0

Connect with

Oracle Java JAXB
This is simple example with minimum annotation to understand JAXB 2.0, or you can say its hello word type of example. If don know what is JAXB 2.0 and you wanted to know, you can read our another post i.e. What is JAXB 2.0 There is no any dependency to run or compile the code. All the libraries are inbuilt in J2SE.

1. Step by step example for JAXB 2.0

– first create POJO class.
– write method to convert from java object to xml
– write method to read from created xml to java object
– call both method from java main class and check your output.

2. Simple POJO Class

File: Customer.java – will be used for converting java to xml and xml to java object.

package com.mysoftkey.jaxb;

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

/**
 * This is simple POJO class with minimum annotation
 * which will be used for JAXB 2.0 marshaling and un-marshaling.
 * 
 * @author Ranjeet.Jha
 * 
 */
@XmlRootElement
public class Customer {

  private String name;
  private int age;
  private int id;

  public String getName() {
	return name;
  }

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

  public int getAge() {
 	return age;
  }
 
  @XmlElement
  public void setAge(int age) {
  	this.age = age;
  }

  public int getId() {
  	return id;
  }

  @XmlAttribute
  public void setId(int id) {
  	this.id = id;
  }
}

3. Method to JAVA Object to XML

The process of converting in JAVA Object to XML in JAXB is known as: Marshaling

/**
 * This method is used to marshal customer object.
 */
private static void marshalCustomer() {

  try {

	// create custome object and populate values to writ into xml
	Customer customer = new Customer();
	customer.setId(1);
	customer.setName("Anushka");
	customer.setAge(5);

	File file = new File(CUSTOMER_FILE);
	JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
	Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

	// to print pretty output on console.
	jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

	jaxbMarshaller.marshal(customer, file);
	jaxbMarshaller.marshal(customer, System.out);

  } catch (JAXBException e) {
	System.err.println("exception occured while converting java object to xml using JAXB , msg: " + e.getMessage());
  }
}

Output:



    5
    Anushka


4. Method to convert XML to JAVA Object

/**
 * This method is used to convert from XML to java object.
 * 
 * @return
 * @throws JAXBException
 * @throws FileNotFoundException
 */
private static Customer getCustomerFromXML() {
  Customer cust = null;
  try {

	JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

	// get variables from our xml file, created before
	System.out.println("Output from our XML File: ");
	Unmarshaller um = jaxbContext.createUnmarshaller();
	cust = (Customer) um.unmarshal(new FileReader(CUSTOMER_FILE));
  } catch (Exception e) {
	System.err.println("exception occured while converting from xml to java object using JAXB , msg: " + e.getMessage());
  }
	return cust;
}

Output:

Output from our XML File: 
id: 1 ,name: Anushka , age: 5

5. Java Client to run

complete class with both method which shown above separately in

/**
 * 
 */
package com.mysoftkey.jaxb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * This is simple example :
 * 
 * 
    *
  • to create from java object to XML
  • *
  • to create form XML to java object
  • *
* * @author Ranjeet.Jha * */ public class CustomerJAXBClient { // doc is a folder under the project, if not then create "doc" folder public static final String CUSTOMER_FILE = "./docs/customer.xml"; public static void main(String[] args) throws FileNotFoundException { try { // convert java object to XML marshalCustomer(); //call method to convert from xml to java object Customer customer = getCustomerFromXML(); System.out.println("id: " + customer.getId() + " , name: " + customer.getName() + " , age: " + customer.getAge() ); } catch (Exception e) { e.printStackTrace(); } } /** * This method is used to marshal customer object. */ private static void marshalCustomer() { try { // create custome object and populate values to writ into xml Customer customer = new Customer(); customer.setId(1); customer.setName("Anushka"); customer.setAge(5); File file = new File(CUSTOMER_FILE); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // to print pretty output on console. jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(customer, file); jaxbMarshaller.marshal(customer, System.out); } catch (JAXBException e) { System.err.println("exception occured while converting java object to xml using JAXB , msg: " + e.getMessage()); } } /** * This method is used to convert from XML to java object. * * @return * @throws JAXBException * @throws FileNotFoundException */ private static Customer getCustomerFromXML() { Customer cust = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); // get variables from our xml file, created before System.out.println("Output from our XML File: "); Unmarshaller um = jaxbContext.createUnmarshaller(); cust = (Customer) um.unmarshal(new FileReader(CUSTOMER_FILE)); } catch (Exception e) { System.err.println("exception occured while converting from xml to java object using JAXB , msg: " + e.getMessage()); } return cust; } }

Your comments are welcome to improve this post. 🙂


Connect with

Leave a Reply

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