欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java写入xml格式数据增强版-可递归进行多层嵌套

程序员文章站 2022-06-29 11:50:35
...
package com.proxy.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author: (le.qiao)
 * @e-mail: qiaolevip@gmail.com
 * @myblog: <a href="http://qiaolevip.iteye.com">http://qiaolevip.iteye.com</a>
 * @date: 2012-8-20
 * 
 */
public class Unlimited {

	public static void main(String[] args) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("A", "1111");
		map.put("B", "2222");
		map.put("C", "3333");
		map.put("D", "4444");

		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("E", "5555");
		map2.put("F", "6666");

		Map<String, Object> map3 = new HashMap<String, Object>();
		map3.put("G", "5555");
		map3.put("H", "6666");

		map2.put("F", map3);
		map.put("D", map2);

		String result = writePro(map);
		System.out.println(result);
	}

	@SuppressWarnings("unchecked")
	public static String writePro(Map<String, Object> map) {
		StringBuffer result = new StringBuffer();
		if (map != null && map.size() > 0) {
			for (Entry<String, Object> map2 : map.entrySet()) {
				if (map2.getValue() instanceof Map) {
					map2.setValue("\n" + writePro((Map<String, Object>) map2.getValue()));
				}

				result.append("<" + map2.getKey() + ">" + map2.getValue() + "</" + map2.getKey() + ">\n");
			}
		}

		return result.toString();
	}
}



<D>
	<E>5555</E>
	<F>
		<G>5555</G>
		<H>6666</H>
	</F>
</D>
<A>1111</A>
<B>2222</B>
<C>3333</C>