1. 程式人生 > >JAVA實現map轉成XML格式

JAVA實現map轉成XML格式

JAVA實現map集合轉成XML格式

例如:

程式碼塊

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

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import cn.sdk.util.StringUtil;

public class XmlUtil {
     private static final String PREFIX_XML = "<xml>";
private static final String SUFFIX_XML = "</xml>";

private static final String PREFIX_CDATA = "<![CDATA[";

private static final String SUFFIX_CDATA = "]]>";

/**
 * 轉化成xml, 單層無巢狀
 * @param map
 * @param isAddCDATA
 * @return
 */
public static String mapToXml(Map<Object, Object> parm, boolean isAddCDATA) {
	StringBuffer strbuff = new StringBuffer(PREFIX_XML);
	if (null != parm) {
		for (Entry<Object, Object> entry : parm.entrySet()) {
			strbuff.append("<").append(entry.getKey()).append(">");
			if (isAddCDATA) {
				strbuff.append(PREFIX_CDATA);
				if (null != entry.getValue()) {
					strbuff.append(entry.getValue());
				}
				strbuff.append(SUFFIX_CDATA);
			} else {
				if (null != entry.getValue()) {
					strbuff.append(entry.getValue());
				}
			}
			strbuff.append("</").append(entry.getKey()).append(">");
		}
	}
	return strbuff.append(SUFFIX_XML).toString();
}


/**
 * @description 將xml字串轉換成map
 * @param xml
 * @return Map
 */
public static Map<String, String> xml2Map(String xml) {
    Map<String, String> map = new HashMap<String, String>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml); // 將字串轉為XML
        Element rootElt = doc.getRootElement(); // 獲取根節點
        @SuppressWarnings("unchecked")
        List<Element> list = rootElt.elements();// 獲取根節點下所有節點
        for (Element element : list) { // 遍歷節點
            map.put(element.getName(), element.getText()); // 節點的name為map的key,text為map的value
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}

}