Tuesday, February 23, 2010

Reading XML files into Java Object, the JAXB way

package com.acme.integration.tools;
import java.io.File;

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

import webservices.processes.CreatePrepaidSubscriberProcess.CreatePrepaidSubscriberwithReturn;

/**
 * Helper class to load Java Objects from an XML document
 * See test methods for usage 
 * @author pierre
 *
 * @param <T>
 */

public class XMLLoader <T> {
    public static void main(String[] args) throws JAXBException {
        testJAXBT();
    }

    private static void testJAXBT() throws JAXBException {
        XMLLoader<CreatePrepaidSubscriberwithReturn> loader = new XMLLoader<CreatePrepaidSubscriberwithReturn>();        CreatePrepaidSubscriberwithReturn result = loader.getObjectFromXMLFile(CreatePrepaidSubscriberwithReturn.class, "resources/CreatePrepaidSubscriber.xml");
        System.out.println(result.getSiebelMessage().getListOfAcmeCreatePrepaidAccountIo().getAcmeAccountLite().get(0).getListOfAcmeSubscriberLite().getAcmeSubscriberLite().get(0).getName());
    }


   
    /**
     * Loads an object from a XML file
     * @param theClass
     * @param fileName
     * @return
     * @throws JAXBException
     */
    public T getObjectFromXMLFile(Class theClass, String fileName) throws JAXBException {
        T result = null;
        JAXBContext jc = JAXBContext.newInstance(theClass.getPackage().getName());
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        result = (T)unmarshaller.unmarshal(new File(fileName));
        return result;
    }

}

No comments: