zoukankan      html  css  js  c++  java
  • map 转换 xml ; xml转map

     1 public class MessageKit {
     2 
     3     public static String map2xml(Map<String, String> map) throws IOException {
     4         Document d = DocumentHelper.createDocument();
     5         Element root = d.addElement("xml");
     6         Set<String> keys = map.keySet();
     7         for(String key:keys) {
     8             root.addElement(key).addText(map.get(key));
     9         }
    10         StringWriter sw = new StringWriter();
    11         XMLWriter xw = new XMLWriter(sw);
    12         xw.setEscapeText(false);
    13         xw.write(d);
    14         return sw.toString();
    15     }
    16 }



    测试方法:
     1     @Test
     2     public void testMsg() {
     3         try {
     4             Map<String,String> maps = new HashMap<String, String>();
     5             maps.put("123", "abc");
     6             maps.put("bcd", "222");
     7             maps.put("bcd", "<abc>ddd</abc>");
     8             System.out.println(MessageKit.map2xml(maps));
     9         } catch (IOException e) {
    10             e.printStackTrace();
    11         }
    12     }

    xml格式字符串转map

    xml格式字符串:

    <xml><ToUserName><![CDATA[gh_46265bed77c6]]></ToUserName><FromUserName><![CDATA[oUigKxHuNI-QMHKzvyYpw1lCY8VQ]]></FromUserName><CreateTime>1459927356</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[sdf]]></Content><MsgId>6270340248959115708</MsgId></xml>

     1     public static Map<String,String> reqMsg2Map(HttpServletRequest req) throws IOException {
     2         String xml = req2xml(req);
     3         System.out.println(xml);
     4         try {
     5             Map<String,String> maps = new HashMap<String, String>();
     6             Document document = DocumentHelper.parseText(xml);
     7             Element root = document.getRootElement();
     8             List<Element> eles = root.elements();
     9             for(Element e:eles) {
    10                 maps.put(e.getName(), e.getTextTrim());
    11             }
    12             return maps;
    13         } catch (DocumentException e) {
    14             e.printStackTrace();
    15         }
    16         return null;
    17     }
  • 相关阅读:
    第三方应用调用应用市场和唤醒APP
    tp5 输入域名即访问指定页面
    反射概述(静态 VS 动态语言)
    自定义注解
    元注解
    内置注解
    什么是注解
    线程小结(代码)
    线程池
    信号灯法
  • 原文地址:https://www.cnblogs.com/a757956132/p/5359501.html
Copyright © 2011-2022 走看看