huliguo
4 天以前 6acf6357094588946b5528f1ef1ed84a0f1037fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.ruoyi.order.util.payment.wx;
 
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
/**
 * XML工具类
 */
public class XMLUtil {
 
    /**
     * 将Map转换为XML字符串
     */
    public static String mapToXml(Map<String, String> params) {
        Document document = DocumentHelper.createDocument();
        // 禁用XML声明
        document.setXMLEncoding(null);  // 关键设置
 
        Element root = document.addElement("xml");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue() != null ? entry.getValue() : "";
            root.addElement(key).setText(value);
        }
        
        return document.asXML();
    }
    
    /**
     * 将XML字符串转换为Map
     */
    public static Map<String, String> xmlToMap(String xmlStr) throws DocumentException {
        Map<String, String> map = new HashMap<>();
        Document document = DocumentHelper.parseText(xmlStr);
        Element root = document.getRootElement();
 
        for (Iterator<?> iterator = root.elementIterator(); iterator.hasNext();) {
            Element element = (Element) iterator.next();
            // 关键修改:获取元素内所有内容(包括CDATA)
            String value = element.getStringValue(); // 自动处理CDATA
            map.put(element.getName(), value);
        }
 
        return map;
    }
}