Reads from xml file and returns the according Object. - Java XML

Java examples for XML:JAXB

Description

Reads from xml file and returns the according Object.

Demo Code


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main{
    public static void main(String[] argv) throws Exception{
        String path = "java2s.com";
        Class clazz = String.class;
        System.out.println(read(path,clazz));
    }//from www.  ja  v  a 2 s.co  m
    /**
     * Reads from xml file and returns the accordingObject.
     * 
     * @param xml
     *            path to xml file
     * @param clazz
     *            class declaration to map from (JAXB)
     * @throws IOException
     *             if file is not existing
     */
    public static <T> T read(String path, Class<T> clazz)
            throws IOException {

        InputStream is = new FileInputStream(new File(path));
        return XmlParser.unmarshal(is, clazz);

    }
    /**
     * Reads xml data from inputstream and returns the accordingObject.
     * 
     * @param <T>
     *            class class declaration to map from (JAXB)
     * @param is
     *            inputstream to read from
     * @param clazz
     *            xml mapping class
     * @return data class
     * @throws IOException
     */
    public static <T> T read(InputStream is, Class<T> clazz)
            throws IOException {

        return XmlParser.unmarshal(is, clazz);

    }
}

Related Tutorials