xml转Map,对象,Map转xml的工具类方法

众所周知,大家在微信开发工程中,由于微信开发文档中,对于消息的接收发送都是基础xml数据的(太坑了),所以我们需要对XML进行解析转换;

1.我们先引入所需要的依赖 dom4j (解析xml的),xstream(可以将对象,以及复杂对象转换为xml);

<dependency>

<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

<!-- 转换xml类 -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.5</version>
</dependency>

2.开始编码 --我会对下面utils类进行解释

(1)此方法用于在微信公众号开发中,后台接收到微信消息后(微信的消息都是xml数据格式),根据request .getInputStream()获取流,然后进行xml解析转换为Map

  ,此方法只能获取到xml的一级元素,但对于开发微信公众号来说,够用了!!

    public static Map<String,String> xmlTOMap(HttpServletRequest request) throws Exception{
        
        Map<String,String> map =new HashMap<String,String>();
        SAXReader reader =new SAXReader();
        InputStream ins=null;
        try {
             ins =request.getInputStream();
        } catch (IOException e) {
            
            e.printStackTrace();
        }
        Document docment =reader.read(ins);//读取流对象
        Element root=docment.getRootElement();
        List<Element> list =root.elements();
        for(Element ele:list) {
            
            map.put(ele.getName(), ele.getText());
        }
        
        return map;
        
        
    }

(2)将xml字符串转换为Map

猜你喜欢

转载自www.cnblogs.com/iscys/p/9501155.html