解析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 requestHeaderMap = new TreeMap();
TreeMap controlMap = new TreeMap();
TreeMap map = new TreeMap();
TreeMap mapHead = new TreeMap();
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 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) entry.getValue(), bodyElem);
} else {
bodyElem.addElement((String) entry.getKey()).addText(
(String) entry.getValue());
}
}
}
}

转载于:https://www.cnblogs.com/wzh0125/p/4462778.html

你可能感兴趣的:(java)