Java tutorial
//package com.java2s; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; 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 { public static void hashMapToXML222(String xmlFile, String xpath, HashMap hashmap) { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootNode = document.createElement(xpath); document.appendChild(rootNode); Set set = hashmap.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); Element em = document.createElement(me.getKey().toString()); em.appendChild(document.createTextNode(me.getValue().toString())); rootNode.appendChild(em); // System.out.println("write " + // me.getKey().toString() + "=" // + me.getValue().toString()); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); FileOutputStream fo = new FileOutputStream(xmlFile); StreamResult result = new StreamResult(fo); transformer.transform(source, result); } catch (Exception ex) { ex.printStackTrace(); } } }