JAXB Example Java

Connect with

JAXB example Java | Hello worlds JAXB exampleLearn step-by-step JAXB example Java. Minimum annotation to understand JAXB 2.0 for new learner, hello word JAXB example first JAXB example.

1. Overview of JAXB Example Java

  • first, create a POJO class.
  • write a method to convert from java object to XML
  • write a method to read from created XML to java object
  • call both methods from the java main class and check your output.

If you new in JAXB you can visit What is JAXB 2.0. There is no dependency to run or compile the code. All the libraries are inbuilt in J2SE.

2. POJO Class for JAXB example

File: Customer.java – will be used for converting java to XML and XML to java object in JAXB example .

>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;

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;
 }

}

6. Reference

oracle.com
I hope you enjoyed this post JAXB example in Java or hello world JAXB example or first JAXB example, visit Core Java tutorial for more blog post.

Your comment is welcome to improve this post. Happy Learning! 🙂


Connect with

Leave a Comment

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