Convert XML JAVA JAXB

Convert XML JAVA JAXB

JAXB (Java Architecture for XML Binding) provide functionality to convert Java classes to XML document and XML to Java classes. This demo will show you how to convert XML to Java object and Java to XML object using JAXB.

  • Unmarshalling: It provides java application ability to convert XML data into Java objects.
  • Marshalling: It provides java application ability to convert Java objects into XML data.

Convert XML JAVA JAXB tools needed:
JDK 1.6 or above (JDK 1.6 comes with JAXB is comes with it). If you are using JDK lower version please include jaxb-impl-lastestVersion.jar and jaxb-api-xxx.jar

  • Sample Persons.XML File which will be used in this example:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1">
        <firstName>Java</firstName>
        <lastName>Honk</lastName>
        <address>
            <streetName>John st.</streetName>
            <location>NY</location>
            <city>NY</city>
            <zip>12345</zip>
        </address>
    </person>
</persons>

 

Convert XML JAVA JAXB steps:

  • To convert XML-JAVA OR JAVA-XML you will have create java class with JAXB annotation. As you see in above XML file which is pretty straight forward we have root element Persons and inside it Person and Address element is there. We will create three classes based on XML file as below:

Persons.java

package com.javahonk.bean;

import java.util.List;

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

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

    @XmlElement(name = "person")
    private List<Person> persons;

    public List<Person> getPersons() {
        return persons;
    }

    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
    
    
}

Person.java

package com.javahonk.bean;

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 Person {
    
    @XmlAttribute(name = "id")
    private String id;
    private String firstName;
    private String lastName;    
    @XmlElement(name = "address")
    List<Address> addressList;

    
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    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 List<Address> getAddressList() {
        return addressList;
    }

    public void setAddressList(List<Address> addressList) {
        this.addressList = addressList;
    }
    
}

Address.java

package com.javahonk.bean;

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

@XmlAccessorType(XmlAccessType.FIELD)
public class Address {
    
    private String streetName;
    private String location;
    private String city;
    private String zip;
    public String getStreetName() {
        return streetName;
    }
    public void setStreetName(String streetName) {
        this.streetName = streetName;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getZip() {
        return zip;
    }
    public void setZip(String zip) {
        this.zip = zip;
    }
    
    
}

 

  • That’s it below class JavaToXMLJAXB.java will convert Java classes to XML file:
package com.javahonk;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.javahonk.bean.Address;
import com.javahonk.bean.Person;
import com.javahonk.bean.Persons;

public class JavaToXMLJAXB {

    public static void main(String[] args) {

        try {

            Persons persons = new Persons();
            List<Person> personList = new ArrayList<Person>();
            
            Person person = new Person();           
            person.setFirstName("Java");
            person.setLastName("Honk");
            
            Address  address = new Address();
            address.setCity("NY");
            address.setLocation("NY");
            address.setStreetName("John St.");
            address.setZip("12345");
            
            List<Address> addressList = new ArrayList<Address>();
            addressList.add(address);           
            person.setAddressList(addressList);
            
            personList.add(person);
            persons.setPersons(personList);         

            //File will be create in project root folder
            File XMLfile = new File("JavaToXMLPerson.xml");
            JAXBContext jaxbContext = JAXBContext
                    .newInstance(Persons.class);
            Marshaller jaxbMarshaller = jaxbContext
                    .createMarshaller();

            jaxbMarshaller.setProperty(Marshaller
                    .JAXB_FORMATTED_OUTPUT, Boolean.TRUE);          

            jaxbMarshaller.marshal(persons, System.out);
            jaxbMarshaller.marshal(persons, XMLfile);
            
            
        } catch (JAXBException e) {
            e.printStackTrace();
        }

    }

}

 

  • XML Output:

Convert XML JAVA JAXB

 

  • Below class will parse XML file and create java classes:
package com.javahonk;

import java.io.File;
import java.util.List;

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

import com.javahonk.bean.Address;
import com.javahonk.bean.Person;
import com.javahonk.bean.Persons;

public class XMLToJavaJAXB {

    public static void main(String[] args) {
        
        File file = new File("src/main/resources/Persons.xml");
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(Persons.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext
                    .createUnmarshaller();
            Persons persons = (Persons) jaxbUnmarshaller
                    .unmarshal(file);
            List<Person> persons2 = persons.getPersons();
            for (Person person : persons2) {
                System.out.println("Id: "+person.getId());
                System.out.println(
                        "First Name: "+person.getFirstName()
                        +" Last Name: "+person.getLastName());
                List<Address> addressList = person.getAddressList();
                for (Address address : addressList) {
                    System.out.println(
                            "Steet: "+address.getStreetName()
                            +" Location: "+address.getLocation()
                            +" City: "+address.getCity()
                            +" Zip: "+address.getZip());
                }
            }
            
        } catch (JAXBException e) {
            e.printStackTrace();
        }

    }

}

 

  • Output:

Convert XML JAVA JAXB

For more information about JAXB please see Oracle JAXB tutorial

That’s it Convert XML JAVA JAXB

Leave a Reply

Your email address will not be published. Required fields are marked *