使用dom4j将xml字符串递归遍历成Map

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XmlStr {

public static void main(String[] args) throws Exception {

String xmlStr = "<returnInfo><resultInfo><returnCode>SUC</returnCode><codeDesc>成功</codeDesc></resultInfo><routeInfo><maxRate>2048</maxRate></routeInfo></returnInfo>";
List<Map<String, String>> resultList = iterateWholeXML(xmlStr);

Map<String, String> retMap = new HashMap<String, String>();
for (int i = 0; i < resultList.size(); i++) {
Map map = (Map) resultList.get(i);

for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
retMap.put(key, (String) map.get(key));

}
}
System.out.println("reMap" + retMap);

}

/**
* 递归解析任意的xml 遍历每个节点和属性
*
* @param xmlStr
*/
public static List<Map<String, String>> iterateWholeXML(String xmlStr) {

List<Map<String, String>> list = new ArrayList<Map<String, String>>();

try {
Document document = DocumentHelper.parseText(xmlStr);
Element root = document.getRootElement();
recursiveNode(root, list);
return list;
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}

/**
* 递归遍历所有的节点获得对应的值
*
* @param
*/
private static void recursiveNode(Element root, List<Map<String, String>> list) {

// 遍历根结点的所有孩子节点
HashMap<String, String> map = new HashMap<String, String>();
for (Iterator iter = root.elementIterator(); iter.hasNext();) {
Element element = (Element) iter.next();
if (element == null)
continue;
// 获取属性和它的值
for (Iterator attrs = element.attributeIterator(); attrs.hasNext();) {
Attribute attr = (Attribute) attrs.next();
System.out.println(attr);
if (attr == null)
continue;
String attrName = attr.getName();
System.out.println("attrname" + attrName);
String attrValue = attr.getValue();

map.put(attrName, attrValue);
}
// 如果有PCDATA,则直接提出
if (element.isTextOnly()) {
String innerName = element.getName();
String innerValue = element.getText();

map.put(innerName, innerValue);
list.add(map);
} else {
// 递归调用
recursiveNode(element, list);
}
}
}

}

posted on 2017-06-21 10:57  Ming9299  阅读(153)  评论(0编辑  收藏  举报