实体类与CDATA类型的xml的转换的工具类
package com.wanhua.util;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.wanhua.weixin.model.ReceEvent;
import com.wanhua.weixin.model.ReplyMsg;
/**
* 实体类与CDATA类型的xml的转换的工具类
*
* @author w_xfpenga
*
* 2014-11-27
*/
public class CDATA2Text {
/**
* 将javaBean对象转成CDATA类型的XML
*
* @param obj
* @return
* @param Object
*
* @return String
*/
public static String Object2CDATA(Object obj) {
Xstream2CDATA xstream2cdata = new Xstream2CDATA();
XStream xStream = xstream2cdata.createXstream();
xStream.autodetectAnnotations(true);
String xml = xStream.toXML(obj);
return xml;
}
/**
* 将CDATA类型的xml转成Map
*
* @param xml
* @return
* @param xml
*
* @return Map
*/
@SuppressWarnings({ "unchecked", "unused" })
public static Map CDATA2Map(String xml) {
Map retMap = new HashMap();
try {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
// 通过输入源构造一个Document
Document doc = (Document) sb.build(source);
Element root = doc.getRootElement();// 指向根节点
List<Element> es = root.getChildren();
if (es != null && es.size() != 0) {
for (Element element : es) {
retMap.put(element.getName(), element.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retMap;
}
}
posted on 2014-12-17 17:28 w_xunfangA 阅读(1136) 评论(0) 编辑 收藏 举报