@date 2019-3-11
*/
public class XMLToMap {
public Map getXML(String requestXml) {
Map map = new HashMap();
// 将字符串转为XML
Document doc;
try {
doc = DocumentHelper.parseText(requestXml);
// 获取根节点
Element rootElm = doc.getRootElement();// 从root根节点获取请求报文
XMLToMap xmlIntoMap = new XMLToMap();
map = xmlIntoMap.parseXML(rootElm, new HashMap());
} catch (DocumentException e) {
e.printStackTrace();
}
return map;
}
/**
将xml解析成map键值对
@param ele
需要解析的xml对象
@param map
入参为空,用于内部迭代循环使用
@return
@see [类、类#方法、类#成员]
*/
private Map parseXML(Element ele, Map map) {
for (Iterator> i = ele.elementIterator(); i.hasNext();) {
Element node = (Element) i.next();
// System.out.println("parseXML node name:" + node.getName());
if (node.attributes() != null && node.attributes().size() > 0) {
for (Iterator> j = node.attributeIterator(); j.hasNext();) {
Attribute item = (Attribute) j.next();
map.put(item.getName(), item.getValue());
}
}
if (node.getText().length() > 0) {
map.put(node.getName(), node.getText());
}
if (node.elementIterator().hasNext()) {
parseXML(node, map);
}
}
return map;
}
/**
将Map转换为对象
@param paramMap
@param cls
@return
*/
public static T parseMap2Object(Map paramMap, Class cls) {
return JSONObject.parseObject(JSONObject.toJSONString(paramMap), cls);
}