JAXB hello world example

JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs :

  1. Marshalling – Convert a Java object into a XML file.
  2. Unmarshalling – Convert XML content into a Java Object.

Technologies used in this article

  1. JDK 1.6
  2. JAXB 2.0

Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.

1. JAXB Dependency

No extra jaxb libraries are required if you are using JDK1.6 or above, because JAXB is bundled in JDK 1.6.

Note
For JDK < 1.6, download JAXB from here, and puts “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

2. JAXB Annotation

For object that need to convert to / from XML file, it have to annotate with JAXB annotation. The annotation are pretty self-explanatory, you can refer to this JAXB guide for detail explanation.

package com.mkyong.core;
 
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
public class Customer {
 
	String name;
	int age;
	int id;
 
	public String getName() {
		return name;
	}
 
	@XmlElement
	public void setName(String name) {
		this.name = name;
	}
 
	public int getAge() {
		return age;
	}
 
	@XmlElement
	public void setAge(int age) {
		this.age = age;
	}
 
	public int getId() {
		return id;
	}
 
	@XmlAttribute
	public void setId(int id) {
		this.id = id;
	}
 
}

3. Convert Object to XML

JAXB marshalling example, convert customer object into a XML file. The jaxbMarshaller.marshal() contains a lot of overloaded methods, find one that suit your output.

package com.mkyong.core;
 
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) {
 
	  Customer customer = new Customer();
	  customer.setId(100);
	  customer.setName("mkyong");
	  customer.setAge(29);
 
	  try {
 
		File file = new File("C:\\file.xml");
		JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
		Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
 
		// output pretty printed
		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
		jaxbMarshaller.marshal(customer, file);
		jaxbMarshaller.marshal(customer, System.out);
 
	      } catch (JAXBException e) {
		e.printStackTrace();
	      }
 
	}
}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
    <age>29</age>
    <name>mkyong</name>
</customer>

4. Convert XML to Object

JAXB unmarshalling example, convert a XML file content into a customer object. The jaxbMarshaller.unmarshal() contains a lot of overloaded methods, find one that suit yours.

package com.mkyong.core;
 
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
 
public class JAXBExample {
	public static void main(String[] args) {
 
	 try {
 
		File file = new File("C:\\file.xml");
		JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
 
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
		System.out.println(customer);
 
	  } catch (JAXBException e) {
		e.printStackTrace();
	  }
 
	}
}

Output

Customer [name=mkyong, age=29, id=100]

References

  1. JAXB Official Website
  2. J2EE 5 JAXB tutorial
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: free movie downloads()

  • Pingback: stream movies()

  • Pingback: Blue Coaster33()

  • Alessandro Reis

    Nice article!

    In the “Convert XML to Object” when it prints customer object I don’t see the same output you had. Do you have any idea?

    You output:
    Customer [name=mkyong, age=29, id=100]

    My output:
    examples.Customer@80d3d6f

  • Tom

    I am trying to print the element values and node names as your shoing in the program but i am not able to print just with System.out.println statement, Could you please help me how to print this?

  • pavan

    How to do this on a list of objects ?

    • Mohit

      Hi Pawan you can use aggregation if you want to marshal list of objects,for eg create one util class with a list of type customer and populate the list of customers into this util class list and now marshal this util class instead of customer.

  • pavan

    How to do this on a List of objects?

  • Navier

    How about using JAXB to generate Java classes from xsd?

  • akanksha

    Thanks to mkyong!!

  • akanksha

    Mkyong examples are the best java examples.Thanks to this site for making java learning interesting!!!

  • Viswas

    Excellent article. I got what i wanted within a few minutes

  • Sumit

    Hi,
    Thanks for a good tutorial. I am stuck with below scenario. Hope to get some solution from you.
    I have an object in my servlet. I want to convert it to xml and send to js file(as a response to jQuery’s ajax call). I wrote an utility method taht will be converting the object to xml. What should be the return type of this method? Please help me to complete this method.

    public static convertObjectToXML(Question question, String className){
    try{
    JAXBContext jaxbContext = JAXBContext.newInstance(Class.forName(className));
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(question, );
    }catch(JAXBException je){
    je.printStackTrace();
    }catch(ClassNotFoundException cnfe){
    cnfe.printStackTrace();
    }
    return ;
    }

    • Sumit

      public static returnType?? convertObjectToXML(Question question, String className){
      try{
      JAXBContext jaxbContext = JAXBContext.newInstance(Class.forName(className));
      Marshaller marshaller = jaxbContext.createMarshaller();
      marshaller.marshal(question, whichStream??);
      }catch(JAXBException je){
      je.printStackTrace();
      }catch(ClassNotFoundException cnfe){
      cnfe.printStackTrace();
      }
      return returns??;
      }

  • Caster

    Thanks mkyong.
    your examples are simple and straight forward, it helps us to understand the technology.

  • biman

    Thanks :)

  • http://valterhenrique.com Valter Henrique

    Thank you very much!

  • subbu

    can you please post an example on how to marshall and unmarshal CDATA using JAXB

    • Karthik

      @Subbu: Did u get the info what u need on marshall and unmarshal CDATA using JAXB? If so, please reply, i am in need of that…

      • subbu

        use eclipselink.jar

        package com.core.template;

        import java.util.ArrayList;

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

        import org.eclipse.persistence.oxm.annotations.XmlCDATA;

        /**
        * @author harsha
        *
        */
        public class Item {

        private String id;
        private String name;
        private String url;

        /**
        * @return the id
        */
        public String getName() {
        return name;
        }
        /**
        * @return the url
        */
        public String getUrl() {
        return url;
        }
        /**
        * @return the implemented
        */
        @XmlAttribute
        public void setId(String id) {
        this.id = id;
        }
        /**
        * @param implemented the implemented to set
        */
        @XmlAttribute
        public void setName(String name) {
        this.name = name;
        }
        /**
        * @param url the url to set
        */
        @XmlCDATA
        public void setUrl(String url) {
        this.url = url;
        }
        }

        you can use @XmlCDATA annotation