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());
}
}
}