Java XML JAXB Unserialize readObjectFromXml(Class jaxbBindClass, String xmlFileName)

Here you can find the source of readObjectFromXml(Class jaxbBindClass, String xmlFileName)

Description

read java object from XML.

License

Open Source License

Parameter

Parameter Description
T - return parameter type
jaxbBindClass - JAXB bind class
xmlFileName - XML filename

Exception

Parameter Description
JAXBException if read XML faild

Return

JAXB bing object

Declaration

public static <T> T readObjectFromXml(Class<T> jaxbBindClass, String xmlFileName) throws JAXBException 

Method Source Code


//package com.java2s;
import java.io.InputStream;

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

import javax.xml.bind.Unmarshaller;

public class Main {
    /**//ww w.j a  v  a  2s. c  o  m
     * read java object from XML.
     * 
     * @param <T> - return parameter type
     * @param jaxbBindClass - JAXB bind class
     * @param xmlFileName - XML filename
     * @return JAXB bing object
     * 
     * @throws JAXBException if read XML faild
     */
    public static <T> T readObjectFromXml(Class<T> jaxbBindClass, String xmlFileName) throws JAXBException {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);
        return readObjectFromXml(jaxbBindClass, is);
    }

    /**
     * read java object from XML.
     * 
     * @param <T> - return parameter type
     * @param jaxbBindClass - JAXB bind class
     * @param is - XML input stream
     * @return JAXB bing object
     * @throws JAXBException if read XML faild
     */
    @SuppressWarnings("unchecked")
    public static <T> T readObjectFromXml(Class<T> jaxbBindClass, InputStream is) throws JAXBException {
        Unmarshaller unmarshaller = createUnmarshaller(jaxbBindClass);
        return (T) unmarshaller.unmarshal(is);
    }

    @SuppressWarnings("rawtypes")
    private static Unmarshaller createUnmarshaller(Class jaxbBindClass) throws JAXBException {
        Unmarshaller unmarshaller = newJAXBContext(jaxbBindClass).createUnmarshaller();
        return unmarshaller;
    }

    @SuppressWarnings("rawtypes")
    private static JAXBContext newJAXBContext(Class jaxbBindClass) throws JAXBException {
        return JAXBContext.newInstance(jaxbBindClass);
    }
}

Related

  1. readExternal(InputStream inputStream, Class clazz)
  2. readJAXB(Class clazz, InputStream is)
  3. readJaxbObject(InputStream inputStream, Class jaxbModelClass)
  4. readObject(Class clazz, File file)
  5. readObjectFromInputStream(final InputStream inputStream, final Class expectedType)
  6. readXmlFileToObj(String path, String packageName)
  7. unserialize(T component, Class returnType)