/**
* 将xml转为key value
* @param xml xml格式字符串
* @return map
*/
public static Map<String,Object> parseXml(String xml,String chartSet) {
if (StringUtils.isEmpty(xml)) {
return null;
}
try {
return parseXml(xml.getBytes(chartSet), chartSet);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解析xml数据
* */
private static Map<String,Object> parseXml(byte[] xmlBytes, String charset) {
SAXReader reader = new SAXReader(false);
InputSource source = new InputSource(new ByteArrayInputStream(xmlBytes));
source.setEncoding(charset);
Map<String,Object> map = new HashMap<>();
try {
Document doc = reader.read(source);
Iterator iter = doc.getRootElement().elementIterator();
while (iter.hasNext()) {
Element e = (Element) iter.next();
if (!e.elementIterator().hasNext()) {
map.put(e.getName(),e.getTextTrim());
continue;
}
Iterator iterator = e.elementIterator();
Map<String,String> param = new HashMap<>();
while (iterator.hasNext()) {
Element el = (Element) iterator.next();
param.put(el.getName(),el.getTextTrim());
}
map.put(e.getName(),param);
}
}catch (Exception e) {
e.printStackTrace();
}
return map;
}