Java 将Map(含多层嵌套List)转换为XML格式
要将Map(含多层嵌套List)转为XML格式,可以使用Java中的XML库,如JDOM或DOM4J。以下是使用JDOM库的示例代码:
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapToXmlConverter {
public static void main(String[] args) {
// 创建一个示例的Map
Map<String, Object> map = new HashMap<>();
map.put('name', 'John');
map.put('age', 25);
List<Object> list = new ArrayList<>();
list.add('item1');
list.add('item2');
map.put('items', list);
// 转换为XML
Element rootElement = new Element('root');
Document document = new Document(rootElement);
convertMapToXml(map, rootElement);
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
String xmlString = xmlOutputter.outputString(document);
System.out.println(xmlString);
}
private static void convertMapToXml(Map<String, Object> map, Element parentElement) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Element element = new Element(key);
if (value instanceof Map) {
convertMapToXml((Map<String, Object>) value, element);
} else if (value instanceof List) {
convertListToXml((List<Object>) value, element);
} else {
element.setText(value.toString());
}
parentElement.addContent(element);
}
}
private static void convertListToXml(List<Object> list, Element parentElement) {
for (Object item : list) {
Element element = new Element('item');
if (item instanceof Map) {
convertMapToXml((Map<String, Object>) item, element);
} else if (item instanceof List) {
convertListToXml((List<Object>) item, element);
} else {
element.setText(item.toString());
}
parentElement.addContent(element);
}
}
}
运行以上代码会生成如下的XML格式输出:
<root>
<items>
<item>item1</item>
<item>item2</item>
</items>
<name>John</name>
<age>25</age>
</root>
这个例子中,我们创建了一个Map对象,包含了多层嵌套的List。然后,我们使用JDOM库将Map转换为XML格式,并使用XMLOutputter将XML格式的结果输出为字符串。
原文地址: https://www.cveoy.top/t/topic/pdYv 著作权归作者所有。请勿转载和采集!