XML字符串和 java对象项目转换

这是之前写,仅供参考(如果缺少jar包可以私信我,CSDN现在下载的东西太费了,动不动就要积分,开源精神所剩无几了,也没办法都需要吃饭,可以理解)

 1 import javax.xml.bind.JAXBContext;
 2 import javax.xml.bind.JAXBException;
 3 import javax.xml.bind.Marshaller;
 4 import javax.xml.bind.Unmarshaller;
 5 
 6 public class XMLUtils{
 7 
 8         /**
 9      * add by scy 通过JAXB生成XML字符串
10      * @param clazz
11      * @return
12      */
13     public static String obj2XML(Object obj){
14         StringWriter sw = new StringWriter(); 
15         String xml = null;
16         try {  
17             // 利用jdk中自带的转换类实现  
18             JAXBContext context = JAXBContext.newInstance(obj.getClass());  
19   
20             Marshaller marshaller = context.createMarshaller();  
21             // 格式化xml输出的格式  
22             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE); 
23             marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
24             marshaller.setProperty(Marshaller.JAXB_ENCODING, "gb2312");
25             // 将对象转换成输出流形式的xml  
26             marshaller.marshal(obj, sw);  
27             xml = sw.toString();
28         } catch (JAXBException e) {  
29             e.printStackTrace(); 
30         }
31         return xml;
32     }
33     
34     /**
35      * add by scy 通过JAXB将XML转化为Object
36      * @param xml
37      * @param clazz
38      * @return
39      */
40     public static <T> Object xml2Obj(String xml,Class<T> clazz){
41         Object obj = null;
42         try {
43             JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
44             Unmarshaller um = jaxbContext.createUnmarshaller();
45             StringReader sr = new StringReader(xml); 
46             obj = clazz.newInstance();
47             obj = um.unmarshal(sr); 
48         } catch (JAXBException e) {
49             // TODO Auto-generated catch block
50             e.printStackTrace();
51         } catch (InstantiationException e) {
52             // TODO Auto-generated catch block
53             e.printStackTrace();
54         } catch (IllegalAccessException e) {
55             // TODO Auto-generated catch block
56             e.printStackTrace();
57         }
58         return obj; 
59     }    
60 }

posted @ 2018-12-05 15:31  平心先生  阅读(3509)  评论(0编辑  收藏  举报