XML工具类 - XmlUtils.java

XML工具类,提供序列化XML、反序列化XML、获取指定节点的值的方法。

 

源码如下:(点击下载 - XmlUtils.javadom4j-1.6.1.jarxstream-1.4.7.jar )

 1 import org.dom4j.Document;
 2 import org.dom4j.DocumentException;
 3 import org.dom4j.DocumentHelper;
 4 import org.dom4j.Element;
 5 import com.thoughtworks.xstream.XStream;
 6 
 7 /**
 8  * XML工具类
 9  * 
10  */
11 public class XmlUtils {
12 
13     private final static String XML_DECLARATION = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
14 
15     private XmlUtils() {
16     }
17 
18     /**
19      * 序列化XML
20      * 
21      * @param obj
22      * @param clazz
23      * @return
24      */
25     public static <T> String toXML(Object obj) {
26         XStream stream = getXStream();
27         stream.processAnnotations(obj.getClass());
28         return new StringBuffer(XML_DECLARATION).append(stream.toXML(obj)).toString();
29     }
30 
31     /**
32      * 反序列化XML
33      * 
34      * @param xmlStr
35      * @param clazz
36      * @return
37      */
38     public static <T> T fromXML(String xmlStr, Class<T> clazz) {
39         XStream stream = getXStream();
40         stream.processAnnotations(clazz);
41         Object obj = stream.fromXML(xmlStr);
42         try {
43             return clazz.cast(obj);
44         } catch (ClassCastException e) {
45             return null;
46         }
47     }
48 
49     /**
50      * 获取指定节点的值
51      * 
52      * @param xpath
53      * @param params
54      * @return
55      */
56     public static String getNodeValue(String xpath, String dataStr) {
57         try {
58             // 将字符串转为xml
59             Document document = DocumentHelper.parseText(dataStr);
60             // 查找节点
61             Element element = (Element) document.selectSingleNode(xpath);
62             if (element != null) {
63                 return element.getStringValue();
64             }
65         } catch (DocumentException e) {
66             e.printStackTrace();
67         }
68         return "";
69     }
70 
71     /**
72      * 获取Xstream实例
73      * 
74      * @return
75      */
76     public static XStream getXStream() {
77         return new XStream();
78     }
79 }

 

posted @ 2016-02-19 12:37  小周JAVA技术分享  阅读(9807)  评论(2编辑  收藏  举报