Map转XML
1、话不多说,直接上代码。
public static String mapToXml(Map<String, Object> map, String encoding,Boolean isAttribute) {
if (CollectionUtils.isEmpty(map)) {
return "";
}
Document document = DocumentHelper.createDocument();
if(StringUtils.isNotBlank(encoding)){
document.setXMLEncoding(encoding);
}
Map.Entry<String, Object> entry = map.entrySet().iterator().next();
if (entry == null || !(entry.getValue() instanceof Map)) {
return "";
}
Element rootElement = document.addElement(entry.getKey());
addElement((Map<String, Object>) entry.getValue(), rootElement, isAttribute);
return document.asXML();
}
然后调用,测试结果
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("name", "keroro");
Map<String, Object> userMap = new HashMap<>();
userMap.put("User", map);
String gbk = XmlUtils.mapToXml(userMap, "GBK", false);
System.out.println(gbk);
}
调用结果如下图: