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:"
+"com.test.jaxb.xngevents.dtd.equipment");

Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();

com.test.jaxb.xngevents.dtd.equipment.XngEvent xngEvent = (com.test.jaxb.xngevents.dtd.equipment.XngEvent)unMarshaller.unmarshal(new 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.




2 comments:

  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

    then

    Utility.class.getClassLoader()...

    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.

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

    at javax.xml.bind.JAXBException.(JAXBException.java:47)

    at javax.xml.bind.ContextFinder.searchcontextPath(ContextFinder.java:205)

    at javax.xml.bind.ContextFinder.find(ContextFinder.java:149)

    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:281)


    Earlier I was able to solve it using
    http://www.coderanch.com/t/561676/XML/Unable-locate-jaxb-properties-package


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

    ReplyDelete