0
点赞
收藏
分享

微信扫一扫

XmlUtil -- xml解析帮组类

niboac 2022-01-10 阅读 36
xmljsonjava

作用

1.xml转map

2.xml转json

需添加的依赖文件

<dependency>
   <groupId>cn.hutool</groupId>
   <artifactId>hutool-all</artifactId>
   <version>5.7.15</version>
</dependency>

<dependency>
   <groupId>org.dom4j</groupId>
   <artifactId>dom4j</artifactId>
   <version>2.1.3</version>
</dependency>


​​​​​
XmlUtil.java

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.asen.demo.constant.XmlSort;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * xml解析帮组类
 * @author asen
 * @date 2022/1/10 15:17
 */
public class XmlUtil {

    /**
     * 标签属性
     */
    private final static String TAG_ATTR = "attr";

    /**
     * 标签真实值
     */
    private final static String TAG_VALUE = "value";

    /**
     * 创建的map类型
     */
    private XmlSort xmlSort = XmlSort.NO_SORT;

    /**
     * 读取xml文件,返回json字符串
     *
     * @param fileName 文件路径
     * @return json字符串
     * @throws DocumentException 异常
     */
    public String xmlToJson(String fileName) throws DocumentException {
        Map<String, Object> xmlMap = xmlToMap(fileName);
        return JSONUtil.toJsonStr(xmlMap);
    }

    /**
     * 读取xml文件,返回map对象
     *
     * @param fileName 文件路径
     * @return map对象
     * @throws DocumentException 异常
     */
    public Map<String, Object> xmlToMap(String fileName) throws DocumentException {
        // 创建saxReader对象
        SAXReader reader = new SAXReader();
        // 通过read方法读取一个文件 转换成Document对象
        Document document = reader.read(new File(fileName));
        //获取根节点元素对象
        Element node = document.getRootElement();
        //遍历所有的元素节点
        Map<String, Object> map = getNewMap();
        // 处理节点
        listNodes(node, map);
        return map;
    }


    /**
     * 遍历当前节点元素下面的所有(元素的)子节点
     *
     * @param node
     */
    public void listNodes(Element node, Map<String, Object> map) {
        Map<String, Object> xiaoMap = getNewMap();
        String nodeKey = node.getName();
        // 获取当前节点的所有属性节点
        List<Attribute> list = node.attributes();
        // 遍历属性节点
        Map<String, Object> attrMap = getNewMap();
        for (Attribute attr : list) {
            attrMap.put(attr.getName(), attr.getValue());
        }
        if (ObjectUtil.isNotEmpty(attrMap)) {
            xiaoMap.put(TAG_ATTR, attrMap);
        }

        if (!("".equals(node.getTextTrim()))) {
            xiaoMap.put(TAG_VALUE, node.getTextTrim());
        }
        // 不为空
        if (ObjectUtil.isEmpty(map.get(nodeKey))) {
            map.put(nodeKey, xiaoMap);
        } else {
            List<Map<String, Object>> childList = null;
            // 获取原来的
            Object obj = map.get(nodeKey);
            if (obj instanceof Iterable) {
                // 非第一个
                childList = (List<Map<String, Object>>) obj;
                childList.add(xiaoMap);
            } else if (obj instanceof Map) {
                // 第一个
                Map<String, Object> childMap = (Map<String, Object>) obj;
                childList = new ArrayList<>();
                childList.add(childMap);
                childList.add(xiaoMap);
            }
            // 添加新的
            map.put(nodeKey, childList);
        }

        // 当前节点下面子节点迭代器
        Iterator<Element> it = node.elementIterator();
        // 遍历
        while (it.hasNext()) {
            // 获取某个子节点对象
            Element e = it.next();
            // 对子节点进行遍历
            listNodes(e, xiaoMap);
        }
    }

    /**
     * 获取一个新的map对象
     *
     * @return map对象
     */
    private Map<String, Object> getNewMap() {
        Object obj = null;
        try {
            obj = xmlSort.getMapClass().newInstance();
            if (obj instanceof Map) {
                return (Map<String, Object>) obj;
            }
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置是否排序
     *
     * @param xmlSort 是否排序对象
     */
    public void setXmlSort(XmlSort xmlSort) {
        this.xmlSort = xmlSort;
    }
}

XmlSort.java

import java.util.HashMap;
import java.util.LinkedHashMap;


/**
 * xml解析顺序是否有序
 * @author ASen
 */

public enum XmlSort{
    /**
     * 有序
     */
    SORT(LinkedHashMap.class,"有序"),
    /**
     * 无序
     */
    NO_SORT(HashMap.class,"无序");

    /**
     *  创建的map字节码对象
     */
    private final Class<?> mapClass;

    /**
     * 顺序名称
     */
    private final String message ;

    XmlSort(Class<?> mapClass, String message) {
        this.mapClass = mapClass;
        this.message = message;
    }

    public Class<?> getMapClass() {
        return mapClass;
    }

    public String getMessage() {
        return message;
    }
}
举报

相关推荐

0 条评论