Java examples to read a XML string or an XML file into a Java object (POJO). XML can be supplied by various means such as an XML file, a URL, or simply a string representation. The populated Java objects can then be used in the application for further processing or workflow.
1. Maven
Start with adding the latest ‘jakarta‘ dependencies for adding the JAXB support (Java 11 onwards).
<dependencies>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>4.0.3</version>
<scope>runtime</scope>
</dependency>
</dependencies>
2. JAXB vs. SAX vs. DOM Parsers
Java provides many approaches for reading an XML file and using the XL content to either print, use in an application, or populate data in Java objects to further use in the 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).
SAXorDOMparser uses the JAXP API to parse an XML document. Both scan the document and logically break it up into discrete pieces (e.g. nodes, text, comments etc).SAXparser 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.DOMparser creates a tree of objects that represents the content and organization of data in theDocumentobject in memory. Here, the application can then navigate through the tree to access the data it needs, and if appropriate, manipulate it.- While
JAXBunmarshal 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
3. Convert XML String to Java Object
To read XML, first get the JAXBContext. It is the 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.
import com.howtodoinjava.xml.model.Employee;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import java.io.StringReader;
public class ReadWriteXML {
public static void main(String[] args) {
// Convert XML String to Java Object
String xmlString = "<employee>" +
" <department>" +
" <id>101</id>" +
" <name>IT</name>" +
" </department>" +
" <location>India</location>" +
" <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();
}
}
}
4. Convert XML File to Java Object
Reading XML from a file is very similar to the above example. You only need to pass File object in place of StringReader object. File will have the reference to '.xml' file to be read in the 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();
}
5. Model
For reference purposes, we are using the following Employee and Department classes. Notice we have used the Jakarta annotations on the fields.
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String firstName;
private String lastName;
private String location;
private Department department;
// constructors, getters, setters, toString()
}
@XmlRootElement(name = "department")
@XmlAccessorType(XmlAccessType.FIELD)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
Integer id;
String name;
// constructors, getters, setters, toString()
}
Drop me your questions in the comments section.
Happy Learning !!
which library we need to implement this
I updated the article.
There is a bug in example code
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.
There shouldn’t be duplicated XmlRootElement and member value should be named not on class annotation but on field annotation.
This is fix:
@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;
@XmlElement(name = “department”)
private Department department;
…
..
…
@XmlAccessorType(XmlAccessType.FIELD)
public class Department2 implements Serializable {
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.
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 ?
Yes, both Employee and Department classes as of in 3rd example
unexpected element (uri:””, local:””). Expected elements are
Querying is possible through jaxb from XML to Java Objects
I will get a input and i need process and send accordingly
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.
I changed
from @XmlAccessorType(XmlAccessType.PROPERTY)
to @XmlAccessorType(XmlAccessType.FIELD)
Now the data is there !!!
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!
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; }