How to use JAXB in java

JAXB, is known as Java Architecture for XML Binding, we can use JAXB annotation to convert Java object to / from XML file or string. JAXB is available in JDK1.6 and above.

1.Marshalling – Converting a Java object into a XML file or string.
2.Unmarshalling – Converting XML into a Java Object.

Here is my Employee Class

package com.vk.test;

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

@XmlRootElement(name="employee")
public class Employee {
	
	private int empId;
	private String empName;

	@XmlElement(name="empId")
	public int getEmpId() {
		return empId;
	}

	public void setEmpId(int empId) {
		this.empId = empId;
	}
	@XmlElement(name="empName")
	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	@Override
	public String toString() {
	return "Employee [empId=" + empId + ", empName=" + empName + "]";
	}

}

1.Marshalling


import java.io.StringWriter;

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

public class PojoToXmlString {

public static void main(String[] args) throws JAXBException {

Employee employee=new Employee();
employee.setEmpId(0555);
employee.setEmpName("vijay");

JAXBContext context=JAXBContext.newInstance(Employee.class);
Marshaller marshaller= context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter stringWriter=new StringWriter();
marshaller.marshal(employee, stringWriter);
System.out.println(stringWriter.toString());
}

}

2.UNMarshalling

import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XMLToObject {
	public static void main(String[] args) throws JAXBException {
		
	String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><employee><empId>365</empId><empName>vijay</empName></employee>";
		
	JAXBContext jaxbContext=JAXBContext.newInstance(Employee.class);
	Unmarshaller unmarshaller=	jaxbContext.createUnmarshaller();
	StringReader reader = new StringReader(xml);
	Employee employee=(Employee)unmarshaller.unmarshal(reader);
		
	System.out.println(employee);
		
	}

}

Posted in Java | Leave a comment