xml格式的字符串转换为map和把map转换为xml格式
/**
* xml格式的字符串转换为map
* @param xml
* @return
*/
@SuppressWarnings("unchecked")
public static Map<String, String> addToXml(String xml) {
Map<String, String> extendMap=new HashMap<String, String>();
if (xml != null && !"".equals(xml)) {
Document doc = null;
try {
doc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
e.printStackTrace();
}
Element root = doc.getRootElement();
Iterator<Element> i = root.elementIterator();
while (i.hasNext()) {
Element e = (Element) i.next();
String key = e.element("key").getText();
String value = e.element("value").getText();
extendMap.put(key, value);
}
}
return extendMap;
}
/**
* 把map转换为xml格式
* @param extendMap
* @return
*/
public static String getToXml(Map<String, String> extendMap) {
Set<Entry<String, String>> set = extendMap.entrySet();
Iterator<Entry<String, String>> i = set.iterator();
Document document = DocumentHelper.createDocument();
document.setXMLEncoding("GBK");
Element booksElement = document.addElement("root");
while (i.hasNext()) {
Map.Entry<String,String> me = (Map.Entry<String,String>) i.next();
Element oElement = booksElement.addElement("keyValue");
Element oElement1 = oElement.addElement("key");
oElement1.addCDATA(me.getKey().toString());
Element oElement2 = oElement.addElement("value");
oElement2.addCDATA(me.getValue().toString());
}
String result = document.asXML();
return result;
}
//获取对象扩展字段数据
Map<String, String> extendMap=new HashMap<String, String>();
MFirmApply apply=new MFirmApply();
apply= (MFirmApply) this.getService().get(entity);
extendMap=addToXml(apply.getExtendData());
request.setAttribute("extendMap", extendMap);
//收集页面扩展字段
Map<String, String> extendMap = new HashMap<String, String>();
extendMap.put("mainProducts", request.getParameter("mainProducts"));
apply.setExtendData(getToXml(extendMap));//把扩展字段放到对象里面
//apply实体类 private String extendData;有这个字段