How to unmarshal/parse XML file using JAXB in Java


This page will walk through How to unmarshal/parse XML file using JAXB in Java. JAXB stands for Java Architecture for XML Binding. JAXB is used to convert XML to Object and Object to XML.

This example can solve your following question also:

  • How to unmarshal XML in Java?
  • How to read XML file data using JAXB in Java?
  • How to convert XML into an Object?

Similar Post: How to parse XML in Java

Add the following dependency to your pom.xml file for binding XML elements and attributes in Object.

<dependency>
	<groupId>javax.xml.bind</groupId>
	<artifactId>jaxb-api</artifactId>
	<version>2.3.1</version>
</dependency>

Let’s start with the actual piece of code. Suppose we have the below XML file which contains family details:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Father name="Kali Ram" age="70" placeOfBirth="Allahabad, India">
	<Son name="Manohar" age="45" placeOfBirth="Lucknow, India">
		<GrandSon name="Pawan" age="30" placeOfBirth="Varanasi, India"/>		
		<GrandSon name="Krishna" age="27" placeOfBirth="Mumbai, India"/>
	</Son>	
	<Son name="Lalchand" age="40" placeOfBirth="Allahabad, India">
		<GrandSon name="Rohit" age="21" placeOfBirth="New Delhi, India"/>
	</Son>	
</Father>

The first step will be to create the POJO of all XML elements, for the above XML file we will create 3 POJO class under some hierarchy.

Father.java
package org.websparrow.xml.parse;

import java.util.List;

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

@XmlRootElement(name = "Father")
@XmlAccessorType(XmlAccessType.FIELD)
public class Father {

	@XmlAttribute(name = "name")
	private String name;
	@XmlAttribute(name = "age")
	private Integer age;
	@XmlAttribute(name = "placeOfBirth")
	private String placeOfBirth;
	@XmlElement(name = "Son")
	private List<Son> sons;

	// Generate Getters and Setters...

	@Override
	public String toString() {
		return "Father [name=" + name + ", age=" + age + ", placeOfBirth=" + placeOfBirth + ", sons=" + sons + "]";
	}
}
Son.java
package org.websparrow.xml.parse;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

@XmlAccessorType(XmlAccessType.FIELD)
public class Son {

	@XmlAttribute(name = "name")
	private String name;
	@XmlAttribute(name = "age")
	private Integer age;
	@XmlAttribute(name = "placeOfBirth")
	private String placeOfBirth;
	@XmlElement(name = "GrandSon")
	private List<GrandSon> grandSons;

	// Generate Getters and Setters...

	@Override
	public String toString() {
		return "Son [name=" + name + ", age=" + age + ", placeOfBirth=" + placeOfBirth + ", grandSons=" + grandSons
				+ "]";
	}
}
GrandSon.java
package org.websparrow.xml.parse;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;

@XmlAccessorType(XmlAccessType.FIELD)
public class GrandSon {

	@XmlAttribute(name = "name")
	private String name;
	@XmlAttribute(name = "age")
	private Integer age;
	@XmlAttribute(name = "placeOfBirth")
	private String placeOfBirth;

	// Generate Getters and Setters...

	@Override
	public String toString() {
		return "GrandSon [name=" + name + ", age=" + age + ", placeOfBirth=" + placeOfBirth + "]";
	}
}

Finally, POJO’s are ready, the second step is to create the JAXBContext object and pass your XML root element POJO to get the new Instance of JAXBContext.

JAXBContext jaxbContext = JAXBContext.newInstance(Father.class);

The third step is to create the Unmarshaller objects and call the unmarshal method.

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Father father = (Father) unmarshaller.unmarshal(fileInputStream);

It will return the resulting content tree. Check out the complete example.

XmlParseUtil.java
package org.websparrow.xml.parse;

import java.io.FileInputStream;

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

public class XmlParseUtil {

	public static void main(String[] args) {

		JAXBContext jaxbContext;
		String fileLocation = "E:\\file\\family-info.xml";

		try (FileInputStream fileInputStream = new FileInputStream(fileLocation)) {

			System.out.println("******** PARSING START ********");

			jaxbContext = JAXBContext.newInstance(Father.class);

			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			Father father = (Father) unmarshaller.unmarshal(fileInputStream);

			System.out.println(father);

			System.out.println("******** PARSING DONE ********");

		} catch (Exception e) {
			System.out.println("******** ERROR: SOMETHING WENT WRONG ********");
			e.printStackTrace();
		}
	}
}

OUTPUT: It will give you the below result.

******** PARSING START ********
Father [name=Kali Ram, age=70, placeOfBirth=Allahabad, India, 
	   sons=[
				Son [name=Manohar, age=45, placeOfBirth=Lucknow, India, 
					grandSons=[
								GrandSon [name=Pawan, age=30, placeOfBirth=Varanasi, India],
								GrandSon [name=Krishna, age=27, placeOfBirth=Mumbai, India]]],
				Son [name=Lalchand, age=40, placeOfBirth=Allahabad, India,
					grandSons=[
								GrandSon [name=Rohit, age=21, placeOfBirth=New Delhi, India]]]]]
******** PARSING DONE ********

To fetch only Son details, your code will be:

father.getSons().stream().forEach(sons -> System.out.println(sons));

It will give you only Son and GrandSon details.

Son [name=Manohar, age=45, placeOfBirth=Lucknow, India, 
	grandSons=[
				GrandSon [name=Pawan, age=30, placeOfBirth=Varanasi, India], 
				GrandSon [name=Krishna, age=27, placeOfBirth=Mumbai, India]
			  ]
	]
Son [name=Lalchand, age=40, placeOfBirth=Allahabad, India, 
	grandSons=[
				GrandSon [name=Rohit, age=21, placeOfBirth=New Delhi, India]
			  ]
	]

And for GrandSon details:

father.getSons().stream()
					.forEach(sons -> sons.getGrandSons().stream()
							.forEach(grandSons -> System.out.println(grandSons)));
GrandSon [name=Pawan, age=30, placeOfBirth=Varanasi, India]
GrandSon [name=Krishna, age=27, placeOfBirth=Mumbai, India]
GrandSon [name=Rohit, age=21, placeOfBirth=New Delhi, India]

References

  1. How to parse XML in Java
  2. JAXB- Unmarshaller Interface

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.