将Xml转为Map集合工具类

java 复制代码
package com.wyh.wx.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageUtil {

    /**
     * 解析微信发来的请求(XML).
     *
     * @param msg 消息
     * @return map
     */
    public static Map<String, String> parseXml(final String msg) {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();

        // 从request中取得输入流
        try (InputStream inputStream = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8.name()))) {
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();

            // 遍历所有子节点
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

}
相关推荐
一米阳光zw2 分钟前
Spring Boot中使用 MDC实现请求TraceId全链路透传
java·spring boot·后端·traceid·mdc
EEG小佬2 分钟前
Jupyter选择内核时如何找到虚拟环境
ide·python·jupyter
文人sec16 分钟前
使用python-pandas-openpyxl编写运营查询小工具
开发语言·python·pandas
王元_SmallA16 分钟前
pgsql:connection failed connection to server at
java·后端
高山上有一只小老虎21 分钟前
购物消费打折
java·算法
tuokuac26 分钟前
@Configuration类中定义的@Bean方法
java
hu_yuchen28 分钟前
问卷系统自动化测试报告
软件测试·python
百锦再1 小时前
第8章 模块系统
android·java·开发语言·python·ai·rust·go
没有bug.的程序员1 小时前
Eureka 注册中心原理与服务注册发现机制
java·spring·云原生·eureka·架构·注册中心·服务注册发现
optimistic_chen1 小时前
【Java EE进阶 --- SpringBoot】统一功能处理
java·spring boot·java-ee·json·统一功能处理