解析传入的XML报文,返回Map<String,Object>

import net.sf.json.xml.XMLSerializer;
public static Map<String,Object> msg_xml2map(String xml){
		XMLSerializer xmlSerializer = new XMLSerializer();
		JSON json = xmlSerializer.read(xml);
		Map<String,Object> maps = Utility.fromJson(json.toString(), java.util.Map.class);
		return removeNullNode(maps);
	}

public static <T> T fromJson(String jsonString, Class<T> clazz) {
		try {
			return mapper.readValue(jsonString, clazz);
		} catch (Exception e) {
			log.error("parse json string error:" + jsonString, e);
			return null;
		}
	}

/**
	 * 
	 * 去除空的map(xml转map时用)
	 * 
	 * @param maps
	 */
	public static Map<String,Object> removeNullNode(Map<String,Object> maps){		
		if(null!=maps){
			 for (Map.Entry<String, Object> m : maps.entrySet()) {
				 if(m.getValue() instanceof Map){				
					 removeNullNode((Map<String,Object>)m.getValue());					 
				 }else{
					 if(m.getValue() instanceof ArrayList){
							List list = (ArrayList) m.getValue();
							if(list.size()==0){
								m.setValue("");
							}
						}
				 }
			 }
		}
		
		return maps;
	}

猜你喜欢

转载自nxdjava.iteye.com/blog/2388496