XML转Map

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;

public class XMLUtil {

	public static void main(String[] args) throws Exception{
		String string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><payment_response><transaction_type>sale</transaction_type><status>approved</status><authorization_code>00058Z</authorization_code> <unique_id>7595ac8643a4512cad4b2b906a2e6637</unique_id><transaction_id>WR1909271704453217</transaction_id> <consumer_id>10583334</consumer_id><response_code>00</response_code> <mode>live</mode><timestamp>2019-09-27T09:05:15Z</timestamp><descriptor>jewelrydemand.com</descriptor> <amount>101</amount><currency>USD</currency><sent_to_acquirer>true</sent_to_acquirer><dynamic_descriptor_params><merchant_name>COLORFULWIN.COM</merchant_name><merchant_city>UK</merchant_city></dynamic_descriptor_params><scheme_transaction_identifier>MRGYH8IUN</scheme_transaction_identifier></payment_response>";
		
		Map<String,Object> map = xmlToMap(string);		
		JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(map));		
	}
	
	/**
     * xml  To  map
     * @throws Exception
     */
    public static Map<String, Object> xmlToMap(String responseXmlTemp) throws DocumentException {
        Document doc = DocumentHelper.parseText(responseXmlTemp);
        Element rootElement = doc.getRootElement();
        Map<String, Object> mapXml = new HashMap<String, Object>();
        elementToMap(mapXml, rootElement);
        return mapXml;
    }
 
    /**
     * 使用递归调用将多层级xml转为map
     *
     * @param map
     * @param rootElement
     */
    private static void elementToMap(Map<String, Object> map, Element rootElement) {
        // 获得当前节点的子节点
        List<Element> childElements = rootElement.elements();
        if (childElements.size() > 0) {
            Map<String, Object> tempMap = new HashMap<String, Object>();
            for (Element e : childElements) {
                elementToMap(tempMap, e);
                map.put(rootElement.getName(), tempMap);
            }
        } else {
            map.put(rootElement.getName(), rootElement.getText());
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值