Wednesday, January 4, 2012

Convert XML to Java Objects

Starting from java 5, JDK has inbuilt support for JAXB. JAXB (Java Architecture for XML Binding) is an efficient way of converting xml to Java objects.

JDK provides a class javax.xml.bind.JAXBContext to create java objects from xml.

Below is the code to demonstrate it:

JAXBContext jaxbContext = JAXBContext.newInstance("com.test.jaxb.xngevents.dtd.cable:"

Unmarshaller unMarshaller = jaxbContext.createUnmarshaller(); xngEvent = ( File("Q1.xml"));

JAXBContext.newInstance method takes list of packages separated by colon. These packages must contain ObjectFactory class or jaxb.index file. When an xsd is converted to JAXB object then ObjectFactory class is automatically created. This means that classes contained in the packages must be schema derived classes. If the classes are not derived then exception like below will be thrown:

javax.xml.bind.JAXBException: doesnt contain ObjectFactory.class or jaxb.index

There is one more overloaded newInstance method in JAXBContext which takes the Class arguments:

Once the JAXBContext is initialized, Unmarshaller is created. Unmarshaller.unmarshal will read the xml file or xml as String and create the java objects.


  1. The overloaded new Instance method's second argument is the class loader and not class.

    You can give the class loader of the current class.

    like this.getClass().getClassLoader()

    or if u r putting it in static method, where u can't access this object

    you can use classname.class.getClassLoader()

    For instance, ur class name is Utility



    I did this in my current project..

    But unfortunately, our product is not running on JDK 1.6, so i had to use Java Web Services Developer pack to get jaxb jars.

  2. I am getting the following exception :
    javax.xml.bind.JAXBException: Unable to locate for package external.rtgs.inquiryXml

    at javax.xml.bind.JAXBException.(

    at javax.xml.bind.ContextFinder.searchcontextPath(

    at javax.xml.bind.ContextFinder.find(

    at javax.xml.bind.JAXBContext.newInstance(

    Earlier I was able to solve it using

    But today, it is giving me the exception, though and bgm.ser is there in the folder that I specified as the first argument of newInstance.