1. 程式人生 > >XML資料轉換為Map工具類-XmlMapUtils

XML資料轉換為Map工具類-XmlMapUtils

架包引用:
<dependency>
  <groupId>dom4j</groupId>
  <artifactId>dom4j</artifactId>
  <version>1.6.1</version>
</dependency>
程式碼:
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

/**
* Copyright (C), 2011-2018 {company} * FileName: com.mina.utils.XmlMapUtils.java * Author: xxx * Email: xxx * Date: 2018/6/15 23:04 * Description: 將xml轉換成Map * History: * <Author><Time><version><desc> * {xxx} 23:04 1.0 Create */ public class XmlMapUtils { /**
* 將xml轉換成Map * @param xml * @return */ public static Map<String, Object> xmlToMap(String xml) { Document doc = null; try { doc = DocumentHelper.parseText(xml); } catch (DocumentException e) { e.printStackTrace(); } Map<String, Object> map = new
HashMap<String, Object>(); if (doc == null) return map; Element rootElement = doc.getRootElement(); element2map(rootElement, map); return map; } private static void element2map(Element elmt, Map<String, Object> map) { if (null == elmt) { return; } String name = elmt.getName(); if (elmt.isTextOnly()) { map.put(name, elmt.getText()); } else { Map<String, Object> mapSub = new HashMap<String, Object>(); List<Element> elements = (List<Element>) elmt.elements(); for (Element elmtSub : elements) { element2map(elmtSub, mapSub); } Object first = map.get(name); if (null == first) { map.put(name, mapSub); } else { if (first instanceof List<?>) { ((List) first).add(mapSub); } else { List<Object> listSub = new ArrayList<Object>(); listSub.add(first); listSub.add(mapSub); map.put(name, listSub); } } } } }