关于写入的原数据被修改的问题
当我输入下面输出语句(没有写UTF-8编码方式)时,运行代码(其他部分正常),我的XML文件原来的中文数据都会被修改???这不是只添加一个新的employee标签内容吗?怎么会影响到其他内容?当我把UTF-8代码添加后,一切都会正常。但是原始数据回不来了 ..TUT..
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
代码如下:
package com.dom4j;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class HrWriter {
public void writeXml() {
String file = "E:\\javaworkspace\\xmltest\\src\\xmltest.xml";
SAXReader reader = new SAXReader();
try {
Document document = reader.read(file);
Element root = document.getRootElement();
Element employee = root.addElement("employee");
employee.addAttribute("no", "3333");
Element name = employee.addElement("name");
name.setText("王五");
Element age = employee.addElement("age");
age.setText("25");
employee.addElement("salary").setText("6434");
Element department = employee.addElement("department");
department.addElement("dname").setText("管理部");
department.addElement("address").setText("杏坛");
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
document.write(writer);
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
HrWriter hr = new HrWriter();
hr.writeXml();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<hr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="xsdtest.xsd">
<employee no="324">
<name>张三</name>
<age>32</age>
<salary>3042</salary>
<department>
<dname>行政部</dname>
<address>大良</address>
</department>
</employee>
<employee no="325">
<name>李四</name>
<age>22</age>
<salary>4042</salary>
<department>
<dname>财务部</dname>
<address>容桂</address>
</department>
</employee>
</hr>
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10205 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星