微信支付api返回的xml转换为Map的方法

举例如下:
<xml>
   <return_code><![CDATA[SUCCESS]]></return_code>
   <return_msg><![CDATA[OK]]></return_msg>
   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
   <mch_id><![CDATA[10000100]]></mch_id>
   <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
   <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
   <result_code><![CDATA[SUCCESS]]></result_code>
   <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
   <trade_type><![CDATA[JSAPI]]></trade_type>
</xml>



/**
     * @description 将xml字符串转换成map
     * @param xml
     * @return Map
     */
    public static Map<String,String> readStringXmlOut(String xml) {
        Map<String,String> map = new HashMap<String,String>();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            List<Element> list = rootElt.elements();//获取根节点下所有节点
            for (Element element : list) {	//遍历节点
				map.put(element.getName(), element.getText()); //节点的name为map的key,text为map的value
			}
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }



执行后

"return_code":"SUCCESS",
"return_msg":"OK",
"appid":"wx2421b1c4370ec43b",
"mch_id":"10000100",
"nonce_str":"IITRi8Iabbblz1Jc",
"sign":"7921E432F65EB8ED0CE9755F0E86D72F",
"result_code":"SUCCESS",
"prepay_id":"wx201411101639507cbf6ffd8b0779950874",
"trade_type":"JSAPI"

你可能感兴趣的:(xml,map,微信api)