XML字符串转为Map

import java.io.ByteArrayInputStream;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLToMapUtil {

public static Map<String, String> xmlToMap(String xml, String charset)
throws UnsupportedEncodingException, DocumentException {

Map<String, String> respMap = new HashMap<String, String>();

SAXReader reader = new SAXReader();
Document doc = reader.read(new ByteArrayInputStream(xml.getBytes(charset)));
Element root = doc.getRootElement();
xmlToMap(root, respMap);
return respMap;
}

public static Map<String, String> xmlToMap(Element tmpElement, Map<String, String> respMap) {

if (tmpElement.isTextOnly()) {
respMap.put(tmpElement.getName(), tmpElement.getText());
return respMap;
}

@SuppressWarnings("unchecked")
Iterator<Element> eItor = tmpElement.elementIterator();
while (eItor.hasNext()) {
Element element = eItor.next();
xmlToMap(element, respMap);
}
return respMap;
}
}

上一篇:vue2 和 webpack 配置环境使用


下一篇:Sql Server 2008修改Sa密码