前端之家收集整理的这篇文章主要介绍了
XML和JAVA实体类的相互转化(微信例子),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
/**
* 扩展xstream,使其支持CDATA块
*
*/
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings("unchecked")
public void startNode(String name,Class clazz) {
super.startNode(name,clazz);
}
protected void writeText(QuickWriter writer,String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
/**
* 图文消息对象转换成xml
*
* @param newsMessage 图文消息对象
* @return xml
*/
public static String newsMessageToXml(NewsMessage newsMessage) {
xstream.alias("xml",newsMessage.getClass());
xstream.alias("item",new Article().getClass());
return xstream.toXML(newsMessage);
}
/**
* 解析微信发来的请求(XML)
*
* @param request
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Map<String,String> parseXml(HttpServletRequest request) {
// 将解析结果存储在HashMap中
Map<String,String> map = new HashMap<String,String>();
// 从request中取得输入流
InputStream inputStream;
try {
inputStream = request.getInputStream();
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
// 遍历所有子节点
for (Element e : elementList)
map.put(e.getName(),e.getText());
// 释放资源
inputStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
inputStream = null;
return map;
}
原文链接:/xml/297978.html