直接利用dom4j生成的xml是不带dom头的,但需要应用中需要带dom头的xml文件,比如fusionchart在加载xml数据文件时 ,要求数据文件为带dom头的xml,下面代码示例如何生成带dom头的xml。
public static Document createDom(Map<String,List> data){
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("graph");
root.addAttribute("caption", "xxx");
// root.addAttribute("decimalPrecision", "xxx");
// root.addAttribute("rotateNames", "xxx");
int colorIndex = 0;
for(Map.Entry<String,List> entry:data.entrySet()){
Element set = root.addElement("set");
set.addAttribute("name", entry.getKey());
set.addAttribute("value",(String)(entry.getValue()).get(0));
set.addAttribute("color", ColorUtil.colorList[colorIndex++]);
}
return doc;
}
public static void writeXmlWithBom(String parentPath,Document doc,String fileName){
try {
String filePath = parentPath+File.separator+fileName+".xml";
String tempFileName = parentPath+File.separator+"temp.xml";
File tempFile = new File(tempFileName);
if(tempFile.exists()){
tempFile.delete();
}
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(tempFileName), format);
writer.write(doc);
writer.close();
FileOutputStream fops = new FileOutputStream(fileName);
//首先添加三个bom头字节
fops.write(new byte[]{(byte)0xEF, (byte)0xBB, (byte)0xBF});
FileWriter fileWriter = new FileWriter(fileName, true);
//使用自己流进行读文件,可以防止中文乱码
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tempFileName)));
String data ="";
while((data = br.readLine())!=null){
fileWriter.write(data);
fileWriter.write("\r\n");
}
fops.close();
br.close();
fileWriter.close();
tempFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
需要注意字节流和字符流的使用,防止出现中文乱码