January 2 2017

JAXB Marshaller Example

JAXB Marshaller Example

JAXB stands for Java Architecture for XML Binding. It provides mechanism to convert Java object to XML file (Marshalling) and XML file into a Java Object (Unmarshalling).

Marshalling

public interface Marshaller

The Marshaller class is responsible for converting Java object to XML data.

Example

JAXB class – Employee.java

package com.answersz.jaxb;

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

@XmlRootElement
public class Employee {

private String department;

private String firstname;

private String surname;

private String uid;

public String getDepartment() {
 return department;
 }

@XmlElement
 public void setDepartment(String department) {
 this.department = department;
 }

public String getFirstname() {
 return firstname;
 }

@XmlElement
 public void setFirstname(String firstname) {
 this.firstname = firstname;
 }

public String getSurname() {
 return surname;
 }

@XmlElement
 public void setSurname(String surname) {
 this.surname = surname;
 }

public String getUid() {
 return uid;
 }

@XmlElement
 public void setUid(String uid) {
 this.uid = uid;
 }

}

JaxbMarshallerExample.java

package com.answersz.jaxb;

import java.io.File;

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

public class JaxbMarshallerExample {

 public static void main(String[] args) {

 try {

 // JAXB Marshaller Example

 // Create the JAXBContext object
 JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);

 // Create the Marshaller object
 Marshaller marshaller = jaxbContext.createMarshaller();

 // output pretty printed
 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

 // Create file
 File file = new File("employee.xml");

 Employee employee = new Employee();
 employee.setSurname("M");
 employee.setFirstname("Amruth");
 employee.setUid("amruthm");
 employee.setDepartment("BSJ");

 // Marshal the content tree rooted at jaxbElement into a file
 marshaller.marshal(employee, file);

 } catch (JAXBException e) {
 e.printStackTrace();
 }

 }
}

employee.xml (after running the above class)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
 <department>BSJ</department>
 <firstname>Amruth</firstname>
 <surname>M</surname>
 <uid>amruthm</uid>
</employee>


Copyright © 2014. All rights reserved.

Posted January 2, 2017 by answersz in category JAXB

Leave a Comment

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

*