listmap转xml
// 注意导入的包是这个
import org.jdom2.Element;
import org.jdom2.Document;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
/**
* 对List 中Map 转换成xml字符串
*
* @param list
* <Map>
* @return String
* @throws IOException
*/
public static String listToXmlString(List<Map> list) throws IOException {
Document result = new Document();
// 根标签,这个根标签的名字自己取,根据需求命名
Element root = new Element("DATASETS");
root.setText("");
if (list != null) {
for (Map map : list) {
Set keys = map.keySet();
Iterator iterator = keys.iterator();
// 字标签(包裹着每一项的标签)根据需求(实际情况)命名
Element data = new Element("DATASET");
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
String value = String.valueOf(map.get(key));
Element node = new Element(key);
node.setText(value);
data.addContent(node);
}
root.addContent(data);
}
}
ArrayList arrayList = new ArrayList();
arrayList.add(root);
result.setContent(arrayList);
String resultXML = docToXml(result);
return resultXML;
}
/**
* 对DOC 文件输出xml字符串
*
* @param doc
* @return String
* @throws IOException
*/
public static String docToXml(org.jdom2.Document doc) throws IOException {
Format format = Format.getPrettyFormat();
format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8,解决中文问题
XMLOutputter xmlout = new XMLOutputter(format);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
xmlout.output(doc, bo);
String xmlStr = bo.toString();
return xmlStr;
}
原list数据
[
{
education=undergraduate,
occupation=programmer,
name=范占国,
weight=150,
age=23,
height=173,
hobby=basketball
},
{
education=undergraduate,
occupation=programmer,
name=王博,
weight=120,
age=22,
height=168,
hobby=game
},
{
education=undergraduate,
occupation=programmer,
name=魏青波,
weight=125,
age=22,
height=170,
hobby=novel
}
]
转化成的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<DATASETS>
<DATASET>
<education>undergraduate</education>
<occupation>programmer</occupation>
<name>张三</name>
<weight>150</weight>
<age>23</age>
<height>173</height>
<hobby>basketball</hobby>
</DATASET>
<DATASET>
<education>undergraduate</education>
<occupation>programmer</occupation>
<name>王一</name>
<weight>120</weight>
<age>22</age>
<height>168</height>
<hobby>game</hobby>
</DATASET>
<DATASET>
<education>undergraduate</education>
<occupation>programmer</occupation>
<name>魏某</name>
<weight>125</weight>
<age>22</age>
<height>170</height>
<hobby>novel</hobby>
</DATASET>
</DATASETS>
标签:xml,String,list,Element,new,programmer
From: https://www.cnblogs.com/Fantasyfzg/p/16881216.html