dom4j实现xml转map,xml转json字符串
dom4j依赖包
<!--dom4j--><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency>
map转为json字符串方法很多,这里使用fastjson
<!--fastjson 版本1.2.78是Fastjson在发布时的最后一个支持Java 1.7的版本--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.78</version></dependency>
dom4j实现xml转map,再使用 fastjson 将map转为json字符串
package com.study;import com.alibaba.fastjson.JSON;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;public class Test {public static void main(String[] args) throws Exception {String xml = "<sites><site><name>RUNOOB</name><url>www.runoob.com</url></site><site><name>Google</name><url>www.google.com</url></site><site><name>Facebook</name><url>www.facebook.com</url></site></sites>";Map<String, Object> map = xml2map(xml);String json = JSON.toJSONString(map);System.out.println(json);}/*** xml转map 不带属性*/public static Map<String, Object> xml2map(String xml) throws DocumentException {// xml必须有一个根节点xml = "<root>" + xml + "</root>";Document document = DocumentHelper.parseText(xml);Element root = document.getRootElement(); //根节点Map<String, Object> map = xml2map(root);return map;}/*** xml转map 不带属性* 如果是兄弟元素,并且兄弟元素的标签相同,那么这些相同名称的兄弟需要合并为一个数组*/private static Map<String, Object> xml2map(Element element) {Map<String, Object> map = new LinkedHashMap<>();List<Element> list = element.elements(); //获取所有子节点if (list.size() > 0) { //有子节点for (Element iter : list) { //遍历所有子节点List<Object> mapList;if (iter.elements().size() > 0) { //子节点还有子节点Map<String, Object> m = xml2map(iter); //递归调用if (map.get(iter.getName()) != null) { //标签名称已经存在,说明是一个数组结构Object obj = map.get(iter.getName());if (obj instanceof List) { //标签的值是数组结构,取出数组添加新的元素mapList = (List) obj; //取出旧值mapList.add(m); //放入新值} else {mapList = new ArrayList<>();mapList.add(obj); //放入旧值mapList.add(m); //放入新值}map.put(iter.getName(), mapList);} else {map.put(iter.getName(), m);}} else { //子节点无子节点if (map.get(iter.getName()) != null) { //标签名称已经存在,说明是一个数组结构Object obj = map.get(iter.getName());if (obj instanceof List) { //标签的值是数组结构,取出数组添加新的元素mapList = (List) obj; //取出旧值mapList.add(iter.getText()); //放入新值} else {mapList = new ArrayList<>();mapList.add(obj); //放入旧值mapList.add(iter.getText()); //放入新值}map.put(iter.getName(), mapList);} else {map.put(iter.getName(), iter.getText());}}}}return map;}}
效果如下:
<sites><site><name>RUNOOB</name><url>www.runoob.com</url></site><site><name>Google</name><url>www.google.com</url></site><site><name>Facebook</name><url>www.facebook.com</url></site>
</sites>
xml转换为json后效果
{"sites": {"site": [{"name": "RUNOOB","url": "www.runoob.com"},{"name": "Google","url": "www.google.com"},{"name": "Facebook","url": "www.facebook.com"}]}
}