MAP和XML之间的转换

引用jar包:dom4j.jar 点击下载


/**
	 * Map转换成Xml
	 * @param map
	 * @return
	 */
	public static String map2Xmlstring(Map map){
		StringBuffer sb = new StringBuffer("");
		sb.append("");
		
		Set set = map.keySet();
        for(Iterator it=set.iterator(); it.hasNext();){
        	String key = it.next();
        	Object value = map.get(key);
        	sb.append("<").append(key).append(">");
        	sb.append(value);
        	sb.append("");
        }
		sb.append("");
		return sb.toString();
	}


/**
	 * Xml string转换成Map
	 * @param xmlStr
	 * @return
	 */
	public static Map xmlString2Map(String xmlStr){
		Map map = new HashMap();
		Document doc;
		try {
			doc = DocumentHelper.parseText(xmlStr);
			Element el = doc.getRootElement();
			map = recGetXmlElementValue(el,map);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}

/**
	 * 循环解析xml
	 * @param ele
	 * @param map
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	private static Map recGetXmlElementValue(Element ele, Map map){
		List eleList = ele.elements();
		if (eleList.size() == 0) {
			map.put(ele.getName(), ele.getTextTrim());
			return map;
		} else {
			for (Iterator iter = eleList.iterator(); iter.hasNext();) {
				Element innerEle = iter.next();
				recGetXmlElementValue(innerEle, map);
			}
			return map;
		}
	}

测试:

public static void main(String[] args) {
		Map map = new HashMap();
		map.put("id1", "1111111");
		map.put("id2", "2222222");
		map.put("id3", "3333333");
		System.out.println(map2Xmlstring(map));

		String xmlStr = "it1it211111113333333";
		System.out.println(xmlString2Map(xmlStr));
	}
结果:

222222211111113333333
{id1=1111111, it1=it1, it2=it2, id3=3333333}



你可能感兴趣的:(JAVA--xml解析,JSON转换成XML,XML转换成JSON)