package com.ruoyi.other.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;
|
}
|
}
|