JAXB Read XML to Java Object Example

Java example to read XML to Objects. XML can be supplied via some .xml file or simply an string representation. The populated Java objects then can be used in application for further processing or workflow.

1) JAXB vs SAX vs DOM

Java provides many approaches to read an XML file and use the XL content to either print, use in application or populate data in Java objects to further use in application lifecycle. The three main APIs used for this purpose are Simple API for XML (SAX), the Document Object Model (DOM) and Java Architecture for XML Binding (JAXB).

  • SAX or DOM parser use the JAXP API to parse an XML document. Both scan the document and logically break it up into discrete pieces (e.g. nodes, text and comment etc).
  • SAX parser starts at the beginning of the document and passes each piece of the document to the application in the sequence it finds it. Nothing is saved in memory so it can’t do any in-memory manipulation.
  • DOM parser creates a tree of objects that represents the content and organization of data in the Document object in memory. Here, application can then navigate through the tree to access the data it needs, and if appropriate, manipulate it.
  • While JAXB unmarshal the document into Java content objects. The Java content objects represent the content and organization of the XML document, and are directly available to your program.

Read More: Read XML with SAX Parser and DOM Parser

2) Convert XML String to Java Object

To read XML, first get the JAXBContext. It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations.

Now get the Unmarshaller instance from JAXBContext. It’s unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.

String xmlString = "<employee>" + 
			"    <department>" + 
			"        <id>101</id>" + 
			"        <name>IT</name>" + 
			"    </department>" + 
			"    <firstName>Lokesh</firstName>" + 
			"    <id>1</id>" + 
			"    <lastName>Gupta</lastName>" + 
			"</employee>";

JAXBContext jaxbContext;
try 
{
	jaxbContext = JAXBContext.newInstance(Employee.class);				

	Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

	Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
	
	System.out.println(employee);
}
catch (JAXBException e) 
{
	e.printStackTrace();
}

Output:

Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

3) Convert XML File to Java Object

Reading XML from file is very similar to above example. You only need to pass File object in place of StringReader object. File will have reference to '.xml' file to be read in file system.

File xmlFile = new File("employee.xml");

JAXBContext jaxbContext;
try 
{
	jaxbContext = JAXBContext.newInstance(Employee.class);				

	Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

	Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);
	
	System.out.println(employee);
}
catch (JAXBException e) 
{
	e.printStackTrace();
}

Output:

Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private Integer id;
	private String firstName;
	private String lastName;
	private Department department;
	
	public Employee() {
		super();
	}

	public Employee(int id, String fName, String lName, Department department) {
		super();
		this.id = id;
		this.firstName = fName;
		this.lastName = lName;
		this.department = department;
	}

	//Setters and Getters

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", 
                        lastName=" + lastName + ", department="+ department + "]";
	}
}

@XmlRootElement(name = "department")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Department implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	Integer id;
	String name;
	
	public Department() {
		super();
	}

	public Department(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	//Setters and Getters

	@Override
	public String toString() {
		return "Department [id=" + id + ", name=" + name + "]";
	}
}

Content of xml file is same as first example.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <department>
        <id>101</id>
        <name>IT</name>
    </department>
    <firstName>Lokesh</firstName>
    <id>1</id>
    <lastName>Gupta</lastName>
</employee>

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

9 thoughts on “JAXB Read XML to Java Object Example”

  1. Hi Lokesh,

    I am getting unmarshalException, I have a string like ‘ saran’.
    By using Jaxb and unescapexml, i am getting unclosed tag error because it is taking as another xml tag.

    Please suggest what should i do to get xml in InputStream to JAVA object.

    Reply
  2. Hi Team,
    I am getting error , when I copy & past this code -jaxbContext = JAXBContext.newInstance(Employee.class);
    not able to find Emplyee.class , do we need another class with Name Employee ?

    Reply
  3. While UnMarshalling I am getting empty member value – the employee object is not null but the value printed is null – XML file loaded successfully too. Using the employee.xml and classes given in this page.

    Reply
    • I changed

      from @XmlAccessorType(XmlAccessType.PROPERTY)
      to @XmlAccessorType(XmlAccessType.FIELD)

      Now the data is there !!!

      Reply
  4. Thank you – this overview is Excellent!

    can you please tell/instruct me as how do you handle multiple elements that are the same, specifically to unmarshal?

    example xml, below the MM and FDE sections can occur multiple times. I’m confused as how to do this. thanks!
    also, how is a section that can be there or not, in the below example there could be an NFDE section or not, if an FDE exists… will this explode the unmarshal process? thanks!

    <RTR>
    <HEAD>
    <IDCMS pn="ABF31A6FNCL0004" vers="4.0"/>
    <DA>2018/12/11 00:15:42</DA>
    <ACD MSN="0160" tail="N504DN" type="A350-900"/>
    <TID>C00000023</TID>
    </HEAD>
    <HEADRTR>
    <FROM>ZSPD</FROM>
    <TO>KLAX</TO>
    <FNBR>DAL88     </FNBR>
    </HEADRTR>
    <ITD>
    <CB>A</CB>
    <FDE disp="n" dm="y">
    <MC>3031H050</MC>
    <MD>A-ICE // &gt; A-ICE SIDESLIP PROBE 2 HEATG</MD>
    <DA>2018/12/11 00:12:42</DA>
    <CDA>2018/12/11 00:14:17</CDA>
    <FPH>8</FPH>
    <LAB>1</LAB>
    </FDE>
    <MM fo="A" occ="5">
    <MC>3413F7EV</MC>
    <MD>PROBE-SSA,2(11FP2)</MD>
    <DA>2018/12/11 00:08:43</DA>
    <ATA>3413</ATA>
    <FPH>8</FPH>
    <FCL>1</FCL>
    <PRIO>high</PRIO>
    <STA>1</STA>
    <SYS name="ADR2" bite_id="3" side="2"/>
    </MM>
    </ITD>
    </RTR>
    
    Reply
  5. thanks for the post, greatly appreciate good info. trying to wrap my head around this unmarshal/marshal business.

    can you answer this question for me. when and where do you use say the XmlElement declaration on marshal and unmarshal? on Marshalling is it placed on the getter methods ? when unmarshalling on the setter?
    I’m mostly concerned with UnMarshalling right now. thank you! me I’m thinking on setter’s cause it needs to be mapped to the pojo element?

        @XmlElement(name="MC")
        public void setMc(String mc) {
            this.mc = mc;
        }
        @XmlElement(name="MC")
        public String getMc(String mc) {
            this.mc = mc;
        }
    
    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.