Java tutorial
//package com.java2s; //License from project: Open Source License import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.*; public class Main { private static final String ENCODING = "GBK"; public static <T> T fromXml(File xmlPath, Class<T> type) { BufferedReader reader = null; StringBuilder sb = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(xmlPath), ENCODING)); String line = null; sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (FileNotFoundException e) { throw new IllegalArgumentException(e.getMessage()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { //ignore } } } return fromXml(sb.toString(), type); } public static <T> T fromXml(String xml, Class<T> type) { if (xml == null || xml.trim().equals("")) { return null; } JAXBContext jc = null; Unmarshaller u = null; T object = null; try { jc = JAXBContext.newInstance(type); u = jc.createUnmarshaller(); object = (T) u.unmarshal(new ByteArrayInputStream(xml.getBytes(ENCODING))); } catch (JAXBException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return object; } }