Java List<Map<String, Object>> to XML String Conversion
To convert a List<Map<String, Object>> to XML string format in Java, you can utilize Java's XML libraries. Here's a code example demonstrating the process:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.util.List;
import java.util.Map;
public class XmlConverter {
public static String convertToXml(List<Map<String, Object>> dataList) throws Exception {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// Create the root element
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement('data');
doc.appendChild(rootElement);
// Iterate through each Map in the List
for (Map<String, Object> data : dataList) {
// Create a child element
Element element = doc.createElement('item');
rootElement.appendChild(element);
// Iterate through each key-value pair in the Map
for (Map.Entry<String, Object> entry : data.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Create a child element
Element childElement = doc.createElement(key);
childElement.appendChild(doc.createTextNode(value.toString()));
element.appendChild(childElement);
}
}
// Convert to a string
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, 'yes');
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
return result.getWriter().toString();
}
public static void main(String[] args) {
List<Map<String, Object>> dataList = List.of(
Map.of('name', 'John', 'age', 25),
Map.of('name', 'Jane', 'age', 30)
);
try {
String xmlString = convertToXml(dataList);
System.out.println(xmlString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This example utilizes the javax.xml package from the Java standard library to create an XML document. First, a root element 'data' is created. Subsequently, the code iterates through each Map within the dataList, generating a child element 'item' for every Map. Next, it iterates through each key-value pair in each Map, creating a child element for each pair and appending it to the corresponding 'item' element.
Finally, the Transformer converts the Document object into an XML string format, which is then returned.
In the main method, a dataList containing two Maps is created. Then, the convertToXml method is invoked to transform it into an XML string, which is then printed to the console.
原文地址: https://www.cveoy.top/t/topic/pcFd 著作权归作者所有。请勿转载和采集!