Convert Java Object To XML Using JAXB

In this article we will see how to convert Java object to XML using JAXB ?

Converting Java object to XML is called as Marshalling & Converting XML to Java object is called as Unmarshalling. In this article we will see Marshalling using JAXB. Here JAXB stands for Java Architecture for XML Binding.

Here we have one class that is Student and its Object we want to convert into XML.

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student {
	
	private long id;

	private String firstName;

	private String lastName;
	
	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.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;
	}

}

Now lets see how to convert object of Student class to XML using JAXB ?

import java.io.File;

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

public class JavaToXml {

	public static void main(String[] args) {
		
		try {
			
			Student student = new Student();
			student.setId(1);
			student.setFirstName("John");
			student.setLastName("Smith");
			
			JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
			
			Marshaller marshaller = jaxbContext.createMarshaller();
			
			File file = new File("src\\main\\resources\\student.xml");
			
			marshaller.marshal(student, file);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

0 Comments