XML字符串转Map格式

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

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class xmlToMapUtils {
	
	/**
	 * xml转map
	 * @param resultList
	 * @return
	 */
	public static Map xmlToMap(String xmlStr){
		List> resultList = iterateWholeXML(xmlStr);
		 Map retMap = new HashMap();
	        for (int i = 0; i < resultList.size(); i++) {
	            Map map = (Map) resultList.get(i);

	            for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
	                String key = (String) iterator.next();
	                retMap.put(key, (String) map.get(key));

	            }
	        }
	        return retMap;
	}
	
	 /**
     * 递归解析任意的xml 遍历每个节点和属性
     * 
     * @param xmlStr
     */
	private static List> iterateWholeXML(String xmlStr) {

        List> list = new ArrayList>();

        try {
            Document document = DocumentHelper.parseText(xmlStr);
            Element root = document.getRootElement();
            recursiveNode(root, list);
            return list;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
	
	/**
     * 递归遍历所有的节点获得对应的值
     * 
     * @param
     */
    private static void recursiveNode(Element root, List> list) {

        // 遍历根结点的所有孩子节点
        HashMap map = new HashMap();
        for (Iterator iter = root.elementIterator(); iter.hasNext();) {
            Element element = (Element) iter.next();
            if (element == null)
                continue;
            // 获取属性和它的值
            for (Iterator attrs = element.attributeIterator(); attrs.hasNext();) {
                Attribute attr = (Attribute) attrs.next();
                System.out.println(attr);
                if (attr == null)
                    continue;
                String attrName = attr.getName();
                System.out.println("attrname" + attrName);
                String attrValue = attr.getValue();

                map.put(attrName, attrValue);
            }
            // 如果有PCDATA,则直接提出
            if (element.isTextOnly()) {
                String innerName = element.getName();
                String innerValue = element.getText();

                map.put(innerName, innerValue);
                list.add(map);
            } else {
                // 递归调用
                recursiveNode(element, list);
            }
        }
    }
    /**
     * 测试
     */
    public static void main(String[] args) {
		String xmlStr = "SUC成功			   2048";
		Map xmlToMap = xmlToMap(xmlStr);
		System.out.println(xmlToMap);
	}
}

 

你可能感兴趣的:(XML字符串转Map格式)