Convert XML To Java Object Using JAXB

In this article we will see how to convert XML to Java object 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 Unmarshalling using JAXB. Here JAXB stands for Java Architecture for XML Binding.

If you want to learn how to convert Java Object to XML then here is article on Marshalling.

Here we have below XML and that we want to convert to Java object that is basically Student.java

XML - This XML is placed inside src\\main\resources and file name is student.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><student><firstName>John</firstName><id>1</id><lastName>Smith</lastName></student>

Student.java
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 convert XML to Java Object using JAXB.
import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

public class XmlToJava {

	public static void main(String[] args) {
		
		try {
			
			File file = new File("src\\main\\resources\\student.xml");
			
			JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
			
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			
			Student student = (Student) unmarshaller.unmarshal(file);
			
			System.out.println(student.getFirstName());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

0 Comments