前言:在项目中与其他第三方系统进行交互,当第三方系统返回的参数为XML格式时,为了方便使用,需要将XML解析为Map集合,以下为实现的步骤:
1、pom引用dom4j的包
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.1</version>
</dependency>
2、具体实现如下:
/**
* xml解析为map的方法
* @param element
* @param maps
* @return
*/
public static <K, V> Map<String, Object> xmlToMap(String xml) throws Exception {
Document document = DocumentHelper.parseText(xml);
Element elements = document.getRootElement();
Map<String, Object> maps = new HashMap<String, Object>();
maps = elementMap(elements,maps);
return maps;
}
/**
* xml解析为map的方法
* @param element
* @param maps
* @return
*/
@SuppressWarnings({ "unchecked", "unused"