标签:
import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import com.google.gson.Gson; import com.thoughtworks.xstream.XStream; public class Test { public static void main(String[] args) throws Exception { XStream xs = new XStream(); FileInputStream fis = new FileInputStream("E:/GitWorkspace/eap-dop/exp-dop/src/main/java/version.xml"); byte[] b = new byte[fis.available()]; fis.read(b); String str = new String(b); Document doc = DocumentHelper.parseText(str); long beginTime = System.currentTimeMillis(); Map<String, Object> map = Test.Dom2Map(doc); System.out.println(new Gson().toJson(map)); } public static Map<String, Object> Dom2Map(Document doc) { Map<String, Object> map = new HashMap<String, Object>(); if (doc == null) { return map; } Element root = doc.getRootElement(); for (Iterator iterator = root.elementIterator(); iterator.hasNext();) { Element e = (Element) iterator.next(); List list = e.elements(); if (list.size() > 0) { map.put(e.getName(), Test.Dom2Map(e)); } else { map.put(e.getName(), e.getText()); } } return map; } public static Map Dom2Map(Element e) { Map map = new HashMap(); List list = e.elements(); if (list.size() > 0) { for (int i = 0; i < list.size(); i++) { Element iter = (Element) list.get(i); List mapList = new ArrayList(); if (iter.elements().size() > 0) { Map m = Test.Dom2Map(iter); if (map.get(iter.getName()) != null) { Object obj = map.get(iter.getName()); if (!obj.getClass().getName().equals("java.util.ArrayList")) { mapList = new ArrayList(); mapList.add(obj); mapList.add(m); } if (obj.getClass().getName().equals("java.util.ArrayList")) { mapList = (List) obj; mapList.add(m); } map.put(iter.getName(), mapList); } else { map.put(iter.getName(), m); } } else { if (map.get(iter.getName()) != null) { Object obj = map.get(iter.getName()); if (!obj.getClass().getName().equals("java.util.ArrayList")) { mapList = new ArrayList(); mapList.add(obj); mapList.add(iter.getText()); } if (obj.getClass().getName().equals("java.util.ArrayList")) { mapList = (List) obj; mapList.add(iter.getText()); } map.put(iter.getName(), mapList); } else { map.put(iter.getName(), iter.getText()); } } } } else { map.put(e.getName(), e.getText()); } return map; } }
标签:
原文地址:http://my.oschina.net/u/2292000/blog/411408