Here you can find the source of read(File file, Class
Parameter | Description |
---|---|
file | XML file. |
typeParameterClass | Class of the main object in the XML file. |
@SuppressWarnings("unchecked") public static <T> T read(File file, Class<T> typeParameterClass)
//package com.java2s; //License from project: Open Source License import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class Main { /**/* w ww . java 2 s .c o m*/ * Reads an XML file and returns the content as an object of the specified class. * @param file XML file. * @param typeParameterClass Class of the main object in the XML file. * @return Content as an object of the specified class. */ @SuppressWarnings("unchecked") public static <T> T read(File file, Class<T> typeParameterClass) { T content = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(typeParameterClass); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); //jaxbUnmarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); content = (T) jaxbUnmarshaller.unmarshal(file); } catch (JAXBException e) { e.printStackTrace(); } return content; } @SuppressWarnings("unchecked") public static <T> T read(String input, Class<T> typeParameterClass) { T content = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(typeParameterClass); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); //jaxbUnmarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); InputStream is = new ByteArrayInputStream(input.getBytes()); content = (T) jaxbUnmarshaller.unmarshal(is); } catch (JAXBException e) { e.printStackTrace(); } return content; } }