这几天用到了xml技术但是发现了个问题就是无法以UTF-8保存xml文件,保存后再次读出的时候会报“Invalid byte 2 of 2-byte UTF-8 sequence.”这样一个错误
试着使用GBK、gb2312编码来生成的xml文件却可以正常的被解析。
后来在网上找到前辈的资料。
public void createXML(String fileName) {
Document doc = org.dom4j.DocumentHelper.createDocument();
Element root = doc.addElement("book");
root.addAttribute("name", "我的图书");
Element childTmp;
childTmp = root.addElement("price");
childTmp.setText("21.22");
Element writer = root.addElement("author");
writer.setText("李四");
writer.addAttribute("ID", "001");
try {
org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(
new FileWriter(fileName));
xmlWriter.write(doc);
xmlWriter.close();
}
catch (Exception e) {
System.out.println(e);
}
}
改为这个就行了。
public void createXML(String fileName) {
Document doc = org.dom4j.DocumentHelper.createDocument();
Element root = doc.addElement("book");
root.addAttribute("name", "我的图书");
Element childTmp;
childTmp = root.addElement("price");
childTmp.setText("21.22");
Element writer = root.addElement("author");
writer.setText("李四");
writer.addAttribute("ID", "001");
try {
//注意这里的修改
org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(
new FileOutputStream(fileName));
xmlWriter.write(doc);
xmlWriter.close();
}
catch (Exception e) {
System.out.println(e);
}
}
就这样就行了、、、、、忙也不多说了,呵呵希望对你们有帮助。