当前位置 : 主页 > 网页制作 > xml >

XmlBeanMap convert

来源:互联网 收集:自由互联 发布时间:2021-06-13
package com.yung.wx.integration.util;import com.thoughtworks.xstream.XStream;import com.yung.configuration.interceptor.XStreamFactory;import java.io.StringReader;import java.lang.reflect.Field;import java.util.HashMap;import java.util.List;
package com.yung.wx.integration.util;import com.thoughtworks.xstream.XStream;import com.yung.configuration.interceptor.XStreamFactory;import java.io.StringReader;import java.lang.reflect.Field;import java.util.HashMap;import java.util.List;import java.util.Map;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;public class XMLBeanUtil {  private static final XStream xStream = XStreamFactory.getXStream();  /**   * xml转对象   * @param xml        xml字符串   * @param bean       bean   * @param ignoreCase 是否不区分大小写匹配   * @return bean   */  public static <T> T xmlToBean(String xml, T bean, boolean ignoreCase) {    Map<String, String> nodeMap = XMLBeanUtil.xmlToMap(xml);    return mapToBean(nodeMap, bean, ignoreCase);  }  /**   * xml转对象   * @param xml xml字符串   * @return Map   */  public static Map<String, String> xmlToMap(String xml) {    try {      SAXReader sax = new SAXReader();//创建一个SAXReader对象      StringReader read = new StringReader(xml);      Document document = sax.read(read);//获取document对象,如果文档无节点,则会抛出Exception提前结束      Element root = document.getRootElement();//获取根节点      Map<String, String> nodeMap = new HashMap<>();      getNode(root, nodeMap);      return nodeMap;    } catch (DocumentException e) {      return new HashMap<>();    }  }  public static <T> T mapToBean(Map<String, String> map, T bean, boolean ignoreCase) {    Field[] fields = bean.getClass().getDeclaredFields();    if (ignoreCase) {      for (Field f : fields) {        for (String k : map.keySet()) {          if (k.equalsIgnoreCase(f.getName())) {            f.setAccessible(true);            try {              f.set(bean, map.get(k));            } catch (IllegalAccessException ignore) {            }          }        }      }    } else {      for (Field f : fields) {        for (String k : map.keySet()) {          if (k.equals(f.getName())) {            f.setAccessible(true);            try {              f.set(bean, map.get(k));            } catch (IllegalAccessException ignore) {            }          }        }      }    }    return bean;  }  private static void getNode(Element root, Map<String, String> nodeMap) {    List<Element> list = root.elements();    for (Element e : list) {      if ("".equals(e.getTextTrim())) {        getNode(e, nodeMap);      } else {        nodeMap.put(e.getName(), e.getTextTrim());      }    }  }  /**   * 对象转xml   * @param obj 对象   * @return String   */  public static String toXml(Object obj) {    xStream.processAnnotations(obj.getClass());    return xStream.toXML(obj);  }}
网友评论