Java XML JAXB Unmarshaller unmarshalXmlToObject(String xmlFilePath, Class clazz)

Here you can find the source of unmarshalXmlToObject(String xmlFilePath, Class clazz)

Description

Consumes the contents of the specified XML file, and creates a new Java object of the specified class that will contain the consumed contents.

License

Open Source License

Parameter

Parameter Description
xmlFilePath an absolute or relative path to the XML file
clazz the target class

Exception

Parameter Description
JAXBException an exception
FileNotFoundException an exception

Return

an object of the target class that is initialized with the contents of the specified XML file

Declaration

public static <T> T unmarshalXmlToObject(String xmlFilePath, Class<T> clazz)
        throws FileNotFoundException, JAXBException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2011 The University of Memphis.  All rights reserved. 
 * This program and the accompanying materials are made available 
 * under the terms of the LIDA Software Framework Non-Commercial License v1.0 
 * which accompanies this distribution, and is available at
 * http://ccrg.cs.memphis.edu/assets/papers/2010/LIDA-framework-non-commercial-v1.0.pdf
 *******************************************************************************/

import java.io.FileNotFoundException;

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

import javax.xml.bind.Unmarshaller;

public class Main {
    /**//from  w ww  .j  a  va2  s .com
     * Consumes the contents of the specified XML file, and creates a new Java
     * object of the specified class that will contain the consumed contents.
     * 
     * @param xmlFilePath
     *            an absolute or relative path to the XML file
     * @param clazz
     *            the target class
     * @return an object of the target class that is initialized with the
     *         contents of the specified XML file
     * @throws JAXBException
     * @throws FileNotFoundException
     */
    public static <T> T unmarshalXmlToObject(String xmlFilePath, Class<T> clazz)
            throws FileNotFoundException, JAXBException {
        if (clazz == null) {
            return null;
        }

        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        @SuppressWarnings("unchecked")
        T result = (T) jaxbUnmarshaller.unmarshal(new java.io.FileInputStream(xmlFilePath));

        return result;
    }
}

Related

  1. unmarshallXml(final String string, final Class type)
  2. unmarshallXMLtoObject(final byte[] xmlObject, final Class objectClass, final URL schemaURL)
  3. unmarshalObject(final InputStream input, final Class clazz)
  4. unmarshalPackage(InputStream pkgStream)
  5. unmarshalXML(String xmlString, Class classType)