/**
* 将map转化为xml类型的字符串
* @param map
* @return
*/
public static String callMapToXML(Map map) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
mapToXMLTest2(map,sb);
sb.append("</xml>");
try {
return sb.toString();
} catch (Exception e) {
}
return null;
}
private static void mapToXMLTest2(Map map,StringBuffer sb) {
Set set = map.keySet();
for (Iterator it = set.iterator(); it.hasNext();) {
String key = (String) it.next();
Object value = map.get(key);
if (null == value)
value = "";
if (value.getClass().getName().equals("java.util.ArrayList")) {
ArrayList list = (ArrayList) map.get(key);
sb.append("<" + key + ">");
for (int i = 0; i < list.size(); i++) {
HashMap hm = (HashMap) list.get(i);
mapToXMLTest2(hm,sb);
}
sb.append("</" + key + ">");
} else {
if (value instanceof HashMap) {
sb.append("<" + key + ">");
mapToXMLTest2((HashMap) value,sb);
sb.append("</" + key + ">");
} else {
sb.append("<" + key + ">" + value + "</" + key + ">");
}
} } } /** * 把xml类型的字符串转化为map * @param responseResult * @return */ public static Map<String,Object> getMapFromXML(String xmlStr) { SAXBuilder builder = new SAXBuilder(); Map<String,Object> map = new HashMap<String,Object>(); try { Reader in = new StringReader(xmlStr); Document doc = builder.build(in); Element root = doc.getRootElement(); List<Element> list = root.getChildren(); for (Element e : list) map.put(e.getName(),e.getText()); return map; } catch (JDOMException e) { } catch (UnsupportedEncodingException e) { } catch (IOException e) { } catch (Exception e) { } return map; }
原文链接:https://www.f2er.com/xml/296422.html