利用dom4j生成带dom的xml文件

利用dom4j生成带bom的xml文件


直接利用dom4j生成的xml是不带bom头的,但需要应用中需要带bom头的xml文件,比如fusionchart在加载xml数据文件时 ,要求数据文件为带bom头的xml,下面代码示例如何生成带bom头的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();
}

   }

需要注意字节流和字符流的使用,防止出现中文乱码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值