XML数据转换为Map工具类-XmlMapUtils

架包引用:
<dependency>
  <groupId>dom4jgroupId>
  <artifactId>dom4jartifactId>
  <version>1.6.1version>
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:
 *               
 * {xxx}   23:04    1.0          Create
 */
public class XmlMapUtils {

    /**
     * 将xml转换成Map
     * @param xml
     * @return
     */
    public static Map xmlToMap(String xml) {
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        if (doc == null)
            return map;
        Element rootElement = doc.getRootElement();
        element2map(rootElement, map);
        return map;
    }

    private static void element2map(Element elmt, Map map) {
        if (null == elmt) {
            return;
        }
        String name = elmt.getName();
        if (elmt.isTextOnly()) {
            map.put(name, elmt.getText());
        } else {
            Map mapSub = new HashMap();
            List elements = (List) 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 listSub = new ArrayList();
                    listSub.add(first);
                    listSub.add(mapSub);
                    map.put(name, listSub);
                }
            }
        }
    }
}
 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(工具类)