package com.ynxbd.wx.wxfactory.utils; import com.alibaba.fastjson.JSON; import com.ynxbd.wx.wxfactory.bean.MedicalNotify; import lombok.extern.slf4j.Slf4j; import org.dom4j.*; import java.util.HashMap; import java.util.List; import java.util.Map; @Slf4j public class XmlHelper { @FunctionalInterface public interface Params { void setMap(Map params); } /** * 写入xml */ public static String mapToXml(Params params) { Map map = new HashMap<>(); params.setMap(map); return mapToXml(map); } /** * 写入xml */ public static String mapToXml(Map params) { //创建一个document Document document = DocumentHelper.createDocument(); //增加根节点 Element root = document.addElement("xml"); Object value; for (Map.Entry entry : params.entrySet()) { value = entry.getValue(); if (value == null) { continue; } root.addElement(entry.getKey()).setText(value.toString()); } return document.asXML(); } // public static void main(String[] args) { // MchBaseResult mchBaseResult = new MchBaseResult(); // mchBaseResult.setReturn_code("SUCCESS"); // mchBaseResult.setReturn_msg("OK"); // Map map = new HashMap<>(); // map.put("return_code", "SUCCESS"); // String s1 = mapToXml(map); // System.out.println(s1); //// String s = XMLConverUtil.convertToXML(map); //// System.out.println(s); // } /** * xml转map(外层) * * @param xml xml * @param isEmpty 是否转换空值 * @return map */ public static Map xmlOuterToMap(String xml, boolean isEmpty) { Map result = new HashMap<>(); if (xml == null || "".equals(xml)) { return result; } Document document; try { document = DocumentHelper.parseText(xml); Element root = document.getRootElement(); // 获取根节点元素对象 List listElement = root.elements(); // 所有一级子节点的list if (!listElement.isEmpty()) { String name, content; for (Element e : listElement) { // 遍历所有一级子节点 name = e.getName(); content = e.getTextTrim(); if (isEmpty) { //可为空 result.put(name, "".equals(content) ? null : content); } else { if (!"".equals(content)) { result.put(name, content); // 沒有则将当前节点作为上级节点的属性对待 } } } } } catch (DocumentException e) { e.printStackTrace(); } return result; } public static void main(String[] args) { String xml = "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "3\n" + "597\n" + "297\n" + "300\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "300\n" + "0\n" + "0\n" + ""; Map stringObjectMap = xmlOuterToMap(xml, false); MedicalNotify medicalNotify = JSON.parseObject(JSON.toJSONString(stringObjectMap), MedicalNotify.class); System.out.println(medicalNotify); } }