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.