java对简单xml的操作
java对xml的操作,对于简单的xml文件,没有二级子节点下面的方法就可以实现:
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class CreateCommonXml {
Map<String, String> map = null;
public CreateCommonXml(Map map,String filepath)
{
this.map = new LinkedHashMap<String, String>();
this.map =map;
this.writeToXml(filepath);
}
public void writeToXml(String filename) {
//FileWriter out;
OutputStreamWriter out;
FileOutputStream fout ;
try {
fout = new FileOutputStream(new File(filename));
out = new OutputStreamWriter(fout,"UTF-8");
out.write("<?xml version="1.0" encoding="UTF-8"?>\n");
Iterator<?> it = map.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
String text = "<" + key + ">" + (String) map.get(key) + "</" + key + ">\n";
System.err.println(text);
out.write(text);
}
out.write("\n");
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}