import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlTest {
public static String generateXml(HashMap map) {
String strXml = null;
if (map != null) {
SAXReader reader = new SAXReader();
Document document = null;
try {
document = reader.read(new File("D:/test.xml"));
} catch (DocumentException e) {
e.printStackTrace();
}
Element root = (Element) document.selectSingleNode("//root");
root.attribute("value").setValue("分布");
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
String value = (String) map.get(key);
Element element = root.addElement("cell").addAttribute("value",
key);
element.addElement("element").addAttribute("type", "数值")
.addAttribute("name", "人数").addText(value);
}
strXml = encodeXml(document, "gb2312");
}
return strXml;
}
private static String encodeXml(Document document, String aEncode) {
// 进行编码转换
StringWriter sw = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(aEncode);
try {
XMLWriter writer = new XMLWriter(format);
writer.setWriter(sw);
writer.write(document);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sw.toString();
}
public static void main(String[] args) {
HashMap map = new HashMap();
map.put("上海", "200");
map.put("北京", "300");
map.put("天津", "300");
System.out.println(generateXml(map));
}
} |