JAXB Read XML to Java Object Example

Java examples to read an XML string or a file into a Java Object (POJO). XML can be supplied by various means such as an XML file, a URL, or a string.

jaxb

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).

  • SAX or DOM parser 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).
  • 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, the 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

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 !!

Source Code on Github

Leave a Comment

  1. 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 {

    Reply
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.