xml转化为Map

方法:

 

public static Map<String, String> changeMap(String xmlDoc) {

if (!xmlDoc.equals("") && (xmlDoc != null)) {
// 创建一个新的字符串
StringReader xmlString = new StringReader(xmlDoc);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(xmlString);
// 创建一个新的SAXBuilder
SAXBuilder saxb = new SAXBuilder();
// 定义返回对象
Map<String, String> reMap = new HashMap<String, String>();

try {
// 通过输入源构造一个Document
Document doc = saxb.build(source);
// 取的根元素
Element root = doc.getRootElement();

// 得到根元素所有子元素的集合
List node = root.getChildren();
Element et = null;

for (int i = 0; i < node.size(); i++) {
// 循环依次得到子元素
et = (Element) node.get(i);
// 得到内层子节点
List subNode = et.getChildren();
if (subNode.size() == 0) {
// 装入到Map中
reMap.put(et.getName(), et.getText());
} else {
Element subEt = null;
for (int j = 0; j < subNode.size(); j++) {
// 循环依次得到子元素
subEt = (Element) subNode.get(j);
// reMap.putAll(changeMap(reMap, subEt));
reMap = changeMap(reMap, subEt);
}
}

}
} catch (Exception e) {
log.error("\n返回XML解析失败," + e.getMessage());
}
return reMap;

} else {
return null;
}

}

/**
*
* @description 递归解析XML
* @param map
* @param et
* @return Map<String, String>
*/
@SuppressWarnings("unchecked")
public static Map<String, String> changeMap(Map<String, String> map,
Element et) {
// 定义返回对象
Map<String, String> reMap = new HashMap<String, String>();
try {
// 得到内层子节点
List subNode = et.getChildren();
reMap.putAll(map);
if (subNode.size() == 0) {

// 装入到Map中
if (reMap.containsKey(et.getName())) {
String key = "";
for (int i = 0; i < 100 * 10; i++) {
key = et.getName() + i;
if (reMap.containsKey(key)) {
continue;
} else {
reMap.put(key, et.getText());
break;
}
}
} else {
reMap.put(et.getName(), et.getText());
}

} else {
Element subEt = null;
for (int i = 0; i < subNode.size(); i++) {
// 循环依次得到子元素
subEt = (Element) subNode.get(i);
reMap = changeMap(reMap, subEt);
}
}
} catch (Exception e) {
log.error("\n返回XML解析失败," + e.getMessage());
}
return reMap;
}

posted on 2015-01-15 09:54  李丶小翼  阅读(189)  评论(0编辑  收藏  举报

导航