XML parsing in JAVA using JAXB (Java Architecture for XML Binding) with example

leave a comment »

Java Architecture for XML Binding (JAXB) is an API for reading and writing / converting Java objects to and from XML documents. It provides two basic functionality. (1) Convert Java objects into XML called Marshalling and (2) Convert XML back to Java object called Unmarshalling. It is very useful to use JAXB api where the specification is complex and changing. JAXB is a part of the Java SE version 1.6. So if you are using JDK 1.6 then no extra libraries are required.

for JDK 1.5 or below JAXB can be download from here and then add “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

JAXB uses annotation to create the XML elements. The annotation are self explanatory, a more detail information can be found here

Let us create a class named Person.java having the JAXB annotation in it, this will used to convert into XML file later in this article.

package com.test.xmlparsing;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

 * @author flanzerc
public class Person {

    private String firstName;
    private String lastName;
    private int age;
    private int phone;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    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;

    public int getPhone() {
        return phone;

    public void setPhone(int phone) {
        this.phone = phone;


The @XmlRootElement defines the top-level element for the XML file in other words the top level element of the XML file should be annotated with XmlRootElement. Its optional elements are name and namespace but by default the class name is used. The following example will explain how does this work. If we write a class as below

@XmlRootElement( name="root" )
public class MyClass{
   private Foo foo;
   // ...

it will generate the following XML content

<?xml version="1.0" encoding="UTF-8"?>

Now to continue with our discussion let us see the java class to generate XML file from our previously created Person class.

package com.test.xmlparsing;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {

    public static void main(String[] args) {

        Person person = new Person();                                           // 1

        try {

            File file = new File("D:\\file.xml");                               // 2
            JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);    // 3
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();         // 4

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 5

            jaxbMarshaller.marshal(person, file);                               // 6
            jaxbMarshaller.marshal(person, System.out);

        } catch (JAXBException e) {


In the above example we created the Person object at (1) and then set the corresponding setters in the following lines. At (2) we created the File object with the path to the XML file named “file.xml”. At (3) the JAXBContext instance is initialized with Person class passed as parameter and then we create the Marshaller at (4).The line that says (at 5)

jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 

is optional but responsible for creating a formatted output. Finally we pass the Person and File object for marshalling which generate the XML as below.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

To convert XML back to JAVA JAXB Unmarshaller is used. The unmarshaller class provides ability to convert XML data into a tree of Java content objects.

package com.test.xmlparsing;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

 * @author flanzerc
public class JAXBUnmarshallerExample {

    public static void main(String args[]) {
        try {
            File file = new File("D:\\file.xml");                               // 1
            JAXBContext jxContext = JAXBContext.newInstance(Person.class);      // 2
            Unmarshaller unmarshaller = jxContext.createUnmarshaller();         // 3

            Person person = (Person) unmarshaller.unmarshal(file);              // 4
            System.out.println("AGE: " + person.getAge());                      // 5
            System.out.println("NAME: " + person.getFirstName());               // 6

            // ......

        } catch (JAXBException ex) {
            Logger.getLogger(JAXBUnmarshallerExample.class.getName()).log(Level.SEVERE, null, ex);


here also we first created the file object from the generated XML file (form the first example) at (1) and initializes the JAXBContext at (2). The Unmarshaller is created at (3) and finally the unmarshalling is done at (4) where we have passed the “file” object as the argument to the unmarshal function. The retrieved values can be seen in the console as below

AGE: 35
About these ads

Written by flanzer

January 25, 2013 at 17:49

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: