XML基础知识,写入数据到XML文件
原文链接: https://blog.csdn.net/spring_model/article/details/54378312
一、写入数据到XML文件中
往XML文件中写入数据,特别要注意编码问题,这里写入数据采用了两种不同的编码。一般情况下如果xml文件时gb2312,就采用第一种方式,如果为UTF-8,就使用第二种方式写入,否则可以会产生中文乱码问题。
(1)、以UTF-8编码写入数据到XML文件,源代码如下:
// An highlighted block
/**
* UTF-8格式:使用XML的Document对象写数据到XML文件 <br>
* @param document xml的document
* @param path xml的所在路径(路径+文件名全称)
* @param encoding 写入数据编码(以UTF-8编码写XML文件,调用时直接写UTF-8就可以,也可以使用其他编码,但这里会乱码)
*/
public static void write2XML(Document document,String path,String encoding){
XMLWriter out = null;
try {
//OutputFormat.createPrettyPrint()主要是写入数据保持xml文件的格式
out = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File(path)),encoding),OutputFormat.createPrettyPrint());
out.write(document);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(out!=null) out.close();
} catch (IOException e) {
UtilException ue = new UtilException("关闭XML输出流失败:"+e.getMessage(),e);
LogUtil.exception(ue);
}
}
}
(2)、以gb2312编码写入数据到XML文件中,源代码如下。
/**
* GB2312格式:使用XML的Document对象写数据到XML文件 <br>
* @param document 对应XML文件的Document对象
* @param path 对应的XML文件路径名称(路径+文件名全称)
*/
public static void write2XML(Document document,String path){
XMLWriter out = null;
try {
//把document的内容写到XML文件中,保持XML特有的格式
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
//设置编码为UTF-8
out = new XMLWriter(new FileOutputStream(new File(path)),format);
out.write(document);
} catch (IOException e) {
UtilException ue = new UtilException("写XML文件出错:"+e.getMessage(),e);
LogUtil.exception(ue);
}finally{
try {
if(out!=null) out.close();
} catch (IOException e) {
UtilException ue = new UtilException("关闭XML输出流失败:"+e.getMessage(),e);
LogUtil.exception(ue);
}
}
}
二、写入数据总结
(1)用字符流向文件写入数据要考虑乱码问题,而用字节流就不必考虑乱码问题
(2)用字符流向文件写入数据默认使用本地码表即"gb2312"
(3)任何对象读入内存都是以"UTF-8"编码的形式存在
(4)默认情况下XMLWriter的write方法是以"UTF-8"的编码形式将内存中的document对象传给FileWriter,所以要想不发生乱码问题,就要使用包装流OutputStreamWriter并给定写入文件时所使用的编码表,或者使用OutputFormat的setEncoding方法指定传给流对象时所使用的编码格式。