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;
}
}

posted @ 2019-03-07 17:35  生之等待  阅读(325)  评论(0编辑  收藏  举报