Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How to convert a Java Object to Xml using JAXB API and Annotations through a Java program?.

Program to demonstrate conversion of a Java Object to Xml using JAXB API and Annotations through a Java program

Steps to convert Object to Xml :

1. Creating a POJO class :

package com.hubberspot.examples;

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

public class Customer {
 private Integer id;
 private String firstName; 
 private String lastName;
 private String email;
 public Customer(){

 public Integer getId() {
  return id;
 public void setId(Integer id) { = id;

 public String getFirstName() {
  return firstName;

 public void setFirstName(String firstName) {
  this.firstName = firstName;

 public String getLastName() {
  return lastName;

 public void setLastName(String lastName) {
  this.lastName = lastName;

 public String getEmail() {
  return email;

 public void setEmail(String email) { = email;

2. Create a conversion class :

package com.hubberspot.examples;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBObjectToXml {
  public static void main(String[] args) throws IOException {

     Customer customer = new Customer();
     try {
       JAXBContext context = JAXBContext.newInstance(Customer.class);
       Marshaller marshaller = context.createMarshaller();
       marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        new BufferedWriter(new FileWriter("Customer.xml")));
     } catch (JAXBException e) {

3. Output of the program - XML file created as "Customer.xml"

© 2021 Learn Java by Examples Template by Hubberspot