java xml 转 map / map 转 xml
程序员文章站
2022-05-19 15:38:14
...
/**
* map转xml map中没有根节点的键
*
* @param map
* @param rootName
* @return
*/
public static Document map2xml(Map<String, Object> map, String rootName) {
Document doc = DocumentHelper.createDocument();// 创建一个Document对象
Element root = DocumentHelper.createElement(rootName); // 创建根节点
doc.add(root);
map2xml(map, root);
return doc;
}
/**
* map转xml
*
* @param map
* @param body
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private static Element map2xml(Map<String, Object> map, Element body) {
Set<Entry<String, Object>> entries = map.entrySet();
for (Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (key.startsWith("@")) {// 属性
body.addAttribute(key.substring(1, key.length()), value.toString());
} else if (key.equals("#text")) { // 有属性时的文本
body.setText(value.toString());
} else {
if (value instanceof java.util.List) {
List list = (List) value;
Object obj;
for (int i = 0; i < list.size(); i++) {
obj = list.get(i);
// list里是map或String,不会存在list里直接是list的
if (obj instanceof java.util.Map) {
Element subElement = body.addElement(key);
map2xml((Map) list.get(i), subElement);
} else {
body.addElement(key).setText((String) list.get(i));
}
}
} else if (value instanceof java.util.Map) {
Element subElement = body.addElement(key);
map2xml((Map) value, subElement);
} else {
body.addElement(key).setText(value.toString());
}
}
}
return body;
}
/**
* 格式化输出xml
*
* @param document
* @return
* @throws DocumentException
* @throws IOException
*/
public static String formatXml(Document document) throws DocumentException, IOException {
// 格式化输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
// format.setEncoding("UTF-8");
StringWriter writer = new StringWriter();
// 格式化输出流
XMLWriter xmlWriter = new XMLWriter(writer, format);
// 将document写入到输出流
xmlWriter.write(document);
xmlWriter.close();
return writer.toString();
}
参照:原博客