解析Map为XML
package Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class demo10 {
public static void main(String[] args) {
TreeMap<String, Object> requestHeaderMap = new TreeMap<String, Object>();
TreeMap<String, Object> controlMap = new TreeMap<String, Object>();
TreeMap<String, Object> map = new TreeMap<String, Object>();
TreeMap<String, Object> mapHead = new TreeMap<String, Object>();
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date());
map.put("_TransactionId", "_TransactionId");
requestHeaderMap.put("version", "1.0");
map.put("requestHeader", requestHeaderMap);
controlMap.put("requesterName", "MGMT");
map.put("control", controlMap);
mapHead.put("Head", map);
Document document = DocumentHelper.createDocument();
document.setXMLEncoding("UTF-8");
Element bodyElem = document.addElement("Message");
parseToXML(mapHead,bodyElem);
String xml = document.asXML();
System.out.println(xml);
}
private static void parseToXML(TreeMap<String, Object> map, Element bodyElem) {
Iterator records = map.entrySet().iterator();
while (records.hasNext()) {
Map.Entry entry = (Map.Entry) records.next();
if (entry.getValue().getClass().equals(TreeMap.class)) {// 子目录
bodyElem = bodyElem.addElement((String) entry.getKey());
parseToXML((TreeMap<String, Object>) entry.getValue(), bodyElem);
} else {
bodyElem.addElement((String) entry.getKey()).addText(
(String) entry.getValue());
}
}
}
}