Collection与XMLDoc相互转换

生成XMLDoc的公共方法
1:产生XMLDOC
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class AJAXXMLDocument
{
  Element root;
  private final String _ROOT_TAG = "ajax-result";
  private final String _LIST_TAG = "l";
  private final String _MAP_TAG = "m";
  private final String _VALUE_TAG = "v";
  private final String _RETURN_FLAG_TAG = "flag";
  private final String _RETURN_MESSAGE_TAG = "message";
  private final String _ATTR_NAME = "n";
  private final String _VALUE_KEY = "k";

  public AJAXXMLDocument()
  {
    this.root = new Element("ajax-result");
  }

  /**
   * @deprecated
   */
  public Document getICSsXMLDocument()
  {
    return new Document(this.root);
  }

  public Document getAJAXXMLDocument()
  {
    return new Document(this.root);
  }

  public void setReturnFlag(String flag)
  {
    Element cell = new Element("flag");
    cell.addContent(flag);
    this.root.addContent(cell);
  }

  public void setReturnMessage(String message)
  {
    Element cell = new Element("message");
    cell.addContent(message);
    this.root.addContent(cell);
  }

  public void addObject(String name, Object o)
  {
    List els;
    int i;
    Element el;
    if (o instanceof List) {
      els = this.root.getChildren("l");
      for (i = 0; (els != null) && (i < els.size()); ++i) {
        el = (Element)els.get(i);
        if ((el.getAttribute("n") != null) && (el.getAttribute("n").getValue().equals(name)))
        {
          this.root.removeContent(el);
          break;
        }
      }
      addListObject((List)o, name);
    } else if (o instanceof Map) {
      els = this.root.getChildren("m");
      for (i = 0; (els != null) && (i < els.size()); ++i) {
        el = (Element)els.get(i);
        if ((el.getAttribute("n") != null) && (el.getAttribute("n").getValue().equals(name)))
        {
          this.root.removeContent(el);
          break;
        }
      }
      addMapObject((Map)o, name);
    } else {
      els = this.root.getChildren("v");
      for (i = 0; (els != null) && (i < els.size()); ++i) {
        el = (Element)els.get(i);
        if ((el.getAttribute("k") != null) && (el.getAttribute("k").getValue().equals(name)))
        {
          this.root.removeContent(el);
          break;
        }
      }
      Element cell = new Element("v");
      cell.setAttribute("k", name);
      cell.addContent("null");
      this.root.addContent(cell);
    }
  }

  private void addMapObject(Map paramMap, String paramName)
  {
    this.root.addContent(toXMLForMap(paramMap, paramName));
  }

  private void addListObject(List paramList, String paramName)
  {
    this.root.addContent(toXMLForList(paramList, paramName));
  }

  private Element toXMLForObject(Object o, String name)
  {
    Element cell = new Element("v");
    if ((name != null) && (name.length() > 0))
      cell.setAttribute("k", name);
    if (o instanceof Date) {
      Date d = (Date)o;
      Calendar c = Calendar.getInstance();
      c.setTime(d);
      SimpleDateFormat vFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      if ((c.get(13) == 0) && (c.get(12) == 0) && (c.get(10) == 0))
      {
        vFormat = new SimpleDateFormat("yyyy-MM-dd");
      } else if (c.get(13) == 0)
        vFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

      cell.addContent(vFormat.format(o));
    } else {
      cell.addContent("null");
    }
    return cell;
  }

  private Element toXMLForMap(Map paramMap, String mapName)
  {
    Element map = new Element("m");
    if ((mapName != null) && (mapName.length() > 0))
      map.setAttribute("n", mapName);
    if (paramMap != null)
      for (Iterator it = paramMap.keySet().iterator(); it.hasNext(); ) {
        String key = (String)it.next();
        if (paramMap.get(key) instanceof Map)
          map.addContent(toXMLForMap((Map)paramMap.get(key), key));
        else if (paramMap.get(key) instanceof List)
          map.addContent(toXMLForList((List)paramMap.get(key), key));
        else
          map.addContent(toXMLForObject(paramMap.get(key), key));
      }


    return map;
  }

  private Element toXMLForList(List paramList, String listName)
  {
    Element list = new Element("l");
    if ((listName != null) && (listName.length() > 0))
      list.setAttribute("n", listName);
    if (paramList != null)
      for (int i = 0; i < paramList.size(); ++i) {
        Object o = paramList.get(i);
        if ((o != null) && (o instanceof Map))
          list.addContent(toXMLForMap((Map)o, ""));
        else if (o instanceof List)
          list.addContent(toXMLForList((List)o, ""));
        else
          list.addContent(toXMLForObject(o, ""));
      }


    return list;
  }

  public static void main(String[] args) {
    OutputStream out = System.out;
    XMLOutputter outputter = new XMLOutputter();
    AJAXXMLDocument icssdoc = new AJAXXMLDocument();
    ArrayList l = new ArrayList();
    Map m = new HashMap();
    m.put("description", null);
    m.put("value", "01");
    m.put("other", "测试");
    l.add(m);
    m = new HashMap();
    m.put("description", "驾驶证");
    m.put("value", "02");
    l.add(m);
    m = new HashMap();
    m.put("description", "军官证");
    m.put("value", "03");
    l.add(m);
    icssdoc.addObject("IDTYPE", l);
    icssdoc.addObject("IDNO", "430**");
    icssdoc.addObject("IDNO", "430**12312");
    try {
      outputter.setEncoding("GBK");
      outputter.output(icssdoc.getAJAXXMLDocument(), out);
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

2:产生XMLDOC、XMLDOC转换Collection
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/*
*  应用Dom4j: 1.解析XML字符串存入map中;
*             2.解析XML文件存入map中;
*             3.解析XMLmap存入String中; 
*             4.XML字符串生成xml文件
*             以上都不支持xml的Attribute属性的解析
*/

public class Dom4jXmlProcessor {

private Element documentRoot; //xml根结点

private LinkedHashMap xmlElementsMap = new LinkedHashMap(); //存放xml的map

private StringBuffer sb = new StringBuffer(); //解析map放入StringBuffer

/*
* 解析XML字符串,存入map中,不支持属性的解析
*
*/
public synchronized LinkedHashMap parseXmlString(String xmlStr) {

LinkedHashMap recursiveMap = new LinkedHashMap();
try {
Document document = DocumentHelper.parseText(xmlStr);
Element docRoot = document.getRootElement();//获取根结点       
// documentRoot = docRoot;
LinkedHashMap rootMap=new LinkedHashMap();
recursiveMap.put(docRoot.getName(),rootMap);
//调用遍历解析xml的函数
ergodicXmlElement(docRoot, rootMap);
System.out.println("========xml字符串解析为map==========="+recursiveMap);
} catch (Exception e) {
e.printStackTrace();
System.out.println("解析xml字符串时出现异常!" + e.getMessage());
}
return recursiveMap;
}

/*
* 直接解析XML文件,存入map中,不支持属性的解析
*
*/
public synchronized LinkedHashMap parseXmlFile(String fileName) {

File inputXml = new File(fileName);
SAXReader saxReader = new SAXReader();
LinkedHashMap recursiveMap = new LinkedHashMap();
try {
Document document = saxReader.read(inputXml);
Element docRoot = document.getRootElement();//获取根结点
documentRoot = docRoot;
//调用遍历解析xml的函数
ergodicXmlElement(docRoot, recursiveMap);
// System.out.println("========xml文件解析为map==========="+this.xmlElementsMap);
} catch (DocumentException e) {
System.out.println("解析xml文件时出现异常!" + e.getMessage());
}
return this.xmlElementsMap;
}

/*
* 解析XMLmap,存入String中,不支持属性的解析
*
*/
public String parseXmlMap(LinkedHashMap xmlMap) {

try {
//调用解析xmlMap的函数
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
ergodicXmlMap(xmlMap);
} catch (Exception e) {
System.out.println("生成XML String时出现异常!" + e.getMessage());
}
return this.sb.toString();
}

/*
* xml字符串生成XML文件
*
*/
public void createXmlFile(String xmlString, String fileName) {
try {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(fileName), format);
Document doc = DocumentHelper.parseText(xmlString);
xmlWriter.write(doc);
xmlWriter.close();
} catch (Exception e) {
System.out.println("xml字符串生成XML文件时出现异常!" + e.getMessage());
}
}

/*
* 遍历解析XmlElement
* 在没有子结点时才存入map<key,String>,否则存入map<key,List>
*
* */
public synchronized void ergodicXmlElement(Element elem, LinkedHashMap loopMap) {
Iterator childElemsIter = elem.elementIterator();
while (childElemsIter.hasNext()) {
Element childElem = (Element) childElemsIter.next();
String name = childElem.getName();
List sameChildElems = elem.elements(name);
if (!sameChildElems.isEmpty() && sameChildElems.size() > 1) {
if (loopMap.get(name) == null)
loopMap.put(name, new LinkedList());
}
List childElems = childElem.elements();
if (!childElems.isEmpty()) {
LinkedHashMap elemMap = new LinkedHashMap();
if (loopMap.get(name) != null && loopMap.get(name) instanceof List) {
((List) loopMap.get(name)).add(elemMap);
} else {
if (loopMap.get(name) == null)
loopMap.put(name, new LinkedList());
((List) loopMap.get(name)).add(elemMap);
}
ergodicXmlElement(childElem, elemMap);
} else {
if (loopMap.get(name) != null && loopMap.get(name) instanceof List) {
((List) loopMap.get(name)).add(childElem.getStringValue());
} else {
loopMap.put(name, childElem.getStringValue());
}
}
}
}

/*
* 遍历解析xmlMap
* 适用范围:本方法只适合 xmlMap的value 为String 或 list类型,而其中的list只能存放map的情况
*
* */
public synchronized void ergodicXmlMap(LinkedHashMap xmlMap) {
try {
if (xmlMap != null) {
Iterator it = xmlMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (value instanceof java.lang.String) {
sb.append("<" + key + ">");
sb.append(value);
sb.append("</" + key + ">");
} else if (value instanceof java.util.LinkedList) {
for (Iterator it1 = ((LinkedList) value).iterator(); it1.hasNext();) {
Object obj = it1.next();
sb.append("<" + key + ">");
ergodicXmlMap((LinkedHashMap) obj);//value为List则递归,直到value为String
sb.append("</" + key + ">");
}
} else if(value == null) { // 如果是null
sb.append("<" + key + ">");
sb.append("</" + key + ">");
}
}
}
} catch (Exception e) {
System.out.println("将存放xml元素的map转化为String时出现异常!" + e.getMessage());
}
}

//测试
/*public static void main(String[] args) {

String fileName = "d:\\demo.xml";
Dom4jXmlProcessor dxp = new Dom4jXmlProcessor();
LinkedHashMap xmlMap = new LinkedHashMap();
// //解析xml文件为map
xmlMap = dxp.parseXmlFile(fileName);
System.out.println("====解析xml文件为map======" + xmlMap);
//解析xmlMap 为xmlString
//     String xmlString = dxp.parseXmlMap(xmlMap);
//     System.out.println("====解析xmlMap 为xmlString======"+xmlString); 
//    //由xmlString 生成xml文件
//    dxp.createXmlFile(xmlString, "d:\\createdemo.xml");
//    //解析xmlString为xmlMap
//    xmlMap = dxp.parseXmlString(xmlString);

}*/

public static void main(String[] args) {
       try {
           String fileName = "d:\\demo.xml";
           File file = new File(fileName);
           InputStream inputStream;
           inputStream = new FileInputStream(file);
           InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
           BufferedReader reader = new BufferedReader(inputStreamReader);
           StringBuffer stringBuffer = new StringBuffer("");
           String line = reader.readLine();
           while (line != null) {
              stringBuffer.append(line);
              line = reader.readLine();
           }
           reader.close();
           Dom4jXmlProcessor dxp = new Dom4jXmlProcessor();
           System.out.println(stringBuffer.toString());
           dxp.parseXmlString(stringBuffer.toString());
          
       } catch (FileNotFoundException e) {

           e.printStackTrace();

       } catch (IOException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }



    }



public Element getDocumentRoot() {
return documentRoot;
}

public void setDocumentRoot(Element documentRoot) {
this.documentRoot = documentRoot;
}

public LinkedHashMap getXmlElementsMap() {
return xmlElementsMap;
}

public void setXmlElementsMap(LinkedHashMap xmlElementsMap) {
this.xmlElementsMap = xmlElementsMap;
}

public StringBuffer getSb() {
return sb;
}

public void setSb(StringBuffer sb) {
this.sb = sb;
}

}

你可能感兴趣的:(java,C++,c,xml,Ajax)