xml格式的字符串转换为map和把map转换为xml格式

/**
  * xml格式的字符串转换为map
  * @param xml
  * @return
  */
 @SuppressWarnings("unchecked")
 public static Map addToXml(String xml) {
  Map extendMap=new HashMap();
  if (xml != null && !"".equals(xml)) {
   Document doc = null;
   try {
    doc = DocumentHelper.parseText(xml);
   } catch (DocumentException e) {
    e.printStackTrace();
   }
   Element root = doc.getRootElement();
   Iterator 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 extendMap) {
  Set> set = extendMap.entrySet();
  Iterator> i = set.iterator();
  Document document = DocumentHelper.createDocument();
  document.setXMLEncoding("GBK");
  Element booksElement = document.addElement("root");
  while (i.hasNext()) {
   Map.Entry me = (Map.Entry) 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 extendMap=new HashMap();
  MFirmApply apply=new MFirmApply();
  apply= (MFirmApply) this.getService().get(entity);
  extendMap=addToXml(apply.getExtendData());
  request.setAttribute("extendMap", extendMap);

 

//收集页面扩展字段
  Map extendMap = new HashMap();

 extendMap.put("mainProducts", request.getParameter("mainProducts"));

apply.setExtendData(getToXml(extendMap));//把扩展字段放到对象里面

 

//apply实体类 private String extendData;有这个字段

你可能感兴趣的:(功能)