package com.blueland.bpm.engine.util;

import java.io.StringReader;

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

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jUtil {
	private static Document getDocument(String xml) {
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			document = saxReader.read(new StringReader(xml));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return document;
	}

	public static Map<String,Object> xmlToMap(String xml) {
		Map elementMap = new HashMap();
		Element root = getDocument(xml).getRootElement();
		// 枚举根节点下所有子节点
		for (Iterator ie = root.elementIterator(); ie.hasNext();) {
			Element element = (Element) ie.next();
			elementMap.put(element.getName(), element.getText());
			// 枚举属性
			for (Iterator ia = element.attributeIterator(); ia.hasNext();) {
				Attribute attribute = (Attribute) ia.next();
			}
			// 枚举当前节点下所有子节点
			for (Iterator ieson = element.elementIterator(); ieson.hasNext();) {
				Element elementSon = (Element) ieson.next();
			}
		}
		return elementMap;
	}

	public static void main(String[] args) {
		System.out
				.println(Dom4jUtil
						.xmlToMap("<fields><userId>lw</userId><userName>龙文</userName></fields>"));
	}
}
