将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;
    }

}
相关推荐
考虑考虑11 分钟前
JDK26的JEP 500属性
java·后端·java ee
全栈练习生15 分钟前
Jev 决策模型
python·ai·1024程序员节
LMT流氓兔16 分钟前
第五单元——第十二课:把脚本整理成项目
java·数据库·python·langchain·1024程序员节
光依旧16 分钟前
day-trader-skill实测:让Claude Code当交易助理,纯Python+确定性+fail-closed
python·量化交易·ai agent·a股·风控·claude code·开源项目实测
yuniko-n21 分钟前
【JUC】四种内存屏障示例
java·1024程序员节
CCblandy1 小时前
前缀缓存命中率不靠引擎靠排列:本机仿真 3 轮,易变字段放开头 98.0%→0.0%
人工智能·python·算法·自然语言处理·性能优化
Sakura_j_h_2 小时前
给 FastAPI 接大模型:超时、重试和 token 成本该怎么管
python·大模型·fastapi·超时重试·token计费
念何架构之路2 小时前
Go reflect 包:结构体反射 —Field、Tag 与 VisibleFields
java·数据库·golang
forest_092 小时前
用Python复刻ClaudeDuet:主动式Agent四件套,定时晨报、后台巡检、危险动作审批(附完整可运行代码)
人工智能·python·架构·prompt·agi
liangbo72 小时前
03-JDK 10/11 局部变量推断与 LTS:var 到底该怎么用
java