Utils 类:
1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.FileWriter; 4 import java.io.InputStreamReader; 5 import java.io.Serializable; 6 import java.io.UnsupportedEncodingException; 7 8 import javax.xml.bind.JAXBContext; 9 import javax.xml.bind.JAXBException; 10 import javax.xml.bind.Marshaller; 11 import javax.xml.bind.Unmarshaller; 12 13 /** 14 * Created by Leo on 2017/2/10. 15 */ 16 public class XmlUtils { 17 @SuppressWarnings({ "unchecked", "rawtypes" }) 18 public static <T extends Serializable> T deserialize(String xmlFilePath, Class clazz) 19 throws FileNotFoundException, JAXBException, UnsupportedEncodingException { 20 JAXBContext context = JAXBContext.newInstance(clazz); 21 Unmarshaller unmarshal = context.createUnmarshaller(); 22 FileInputStream fis = new FileInputStream(xmlFilePath); 23 InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 24 return (T) unmarshal.unmarshal(isr); 25 } 26 27 public static <T> void serialize(T obj, String xmlFilePath) { 28 FileWriter writer = null; 29 try { 30 JAXBContext context = JAXBContext.newInstance(obj.getClass()); 31 Marshaller marshal = context.createMarshaller(); 32 marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 33 marshal.marshal(obj, System.out); 34 writer = new FileWriter(xmlFilePath); 35 marshal.marshal(obj, writer); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40 41 }