Java tutorial
//package com.java2s; import java.io.StringWriter; import java.util.Map; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main { private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance(); public static <K, V> String mapToXml(Map<K, V> map, String rootName, String childName, String keyName, String valueName) throws TransformerException, ParserConfigurationException { Document document = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder().newDocument(); Element root = document.createElement(rootName); document.appendChild(root); for (Map.Entry<K, V> errorCodeReport : map.entrySet()) { Element s = document.createElement(childName); root.appendChild(s); s.setAttribute(keyName, errorCodeReport.getKey().toString()); s.setAttribute(valueName, errorCodeReport.getValue().toString()); } return getStringFromDocument(document); } public static String getStringFromDocument(Document doc) { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tf.newTransformer(); transformer.transform(domSource, result); } catch (Exception e) { throw new IllegalStateException(e); } return writer.toString(); } }