map.toString()是这样子的~
{welcome-file-list={welcome-file=[index.html, {a=[{b=[{c=[c1c1c1c1c1c1, c2c2c2c2c2c2]}, b2b2b2b2]}, 22222, 33333]}, index.jsp, default.html, default.htm, default.jsp]}, display-name=ask-ssh, context-param={param-value=classpath:applicationContext.xml, param-name=contextConfigLocation},
filter-mapping={url-pattern=/*, filter-name=struts2}, listener={listener-class=org.springframework.web.context.ContextLoaderListener}, filter={filter-class=org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter, filter-name=struts2}}
观察发现,由map 套 list 套 map
思路:
需要注意的是:在每个循环开始和结尾都需要加上 sb.append("<" + key + ">"); sb.append("</" + key + ">");
而中间是否要放值,取决于你是Map?是List?是String? 只有String才放值
public static String map2Dom(Map<String, Object> map) { // iterator法,遍历map Iterator keyIterator = map.keySet().iterator(); StringBuffer sb = new StringBuffer(); while (keyIterator.hasNext()) { String key = (String) keyIterator.next(); Object value = map.get(key); // 如果value是map则调用map2Dom if ("java.util.HashMap".equals(value.getClass().getName())) { mapAppend(sb, key, value); } else { // 不是map,判断是否是list if ("java.util.ArrayList".equals(value.getClass().getName())) { for (Object tmpObject : (List) value) { // 如果是map,则调用map2Dom // 此时就变成一开始的样子了`~~ if ("java.util.HashMap".equals(tmpObject.getClass() .getName())) { mapAppend(sb, key, tmpObject); } else { // "java.lang.String" stringAppend(sb, key, tmpObject); } } } else { stringAppend(sb, key, value); } } } return sb.toString(); } private static void stringAppend(StringBuffer sb, String key, Object tmpObject) { sb.append("<" + key + ">"); sb.append(tmpObject); sb.append("</" + key + ">"); } private static void mapAppend(StringBuffer sb, String key, Object tmpObject) { sb.append("<" + key + ">"); sb.append(map2Dom((Map<String, Object>) tmpObject)); sb.append("</" + key + ">"); }
原文地址:http://blog.csdn.net/tragedyxd/article/details/43971489