Java tutorial
//package com.java2s; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; 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; } }