dom4j向xml文件中写数据乱码问题解决

这是原先利用dom4j向xml文件中写数据的代码

public void save(Student e) {
		// TODO Auto-generated method stub
		Document doc = DocumentHelper.createDocument();
		doc = DomUtils.parse("db.xml");
		Element root = (Element) doc.selectSingleNode("/students");
		Element stu = root.addElement("student").addAttribute("id", e.getId()).addAttribute("name", e.getName());
		List score = e.getScore();
		for (Score s : score) {
			Element sco = stu.addElement("score").addAttribute("project", s.getProject()).addAttribute("value",
					s.getValue());
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		try {
			XMLWriter writer = new XMLWriter(new FileWriter("db.xml"), format);
			writer.write(doc);
			writer.close();

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}


db.xml文件内容如下:

dom4j向xml文件中写数据乱码问题解决_第1张图片

进行操作如截图

dom4j向xml文件中写数据乱码问题解决_第2张图片

此时的db.xml文件内容会发生乱码,不仅新插入的数据乱码,原来的数据同样也发生乱码

dom4j向xml文件中写数据乱码问题解决_第3张图片

解决办法:

设置format编码格式为“utf-8”,再将字符流改为字节流

即将XMLWriter writer = new XMLWriter(new FileWriter("db.xml"), format);
改为XMLWriter writer = new XMLWriter(new FileOutputStream("db.xml"), format);

OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		try {
			XMLWriter writer = new XMLWriter(new FileOutputStream("db.xml"), format);
			// XMLWriter writer = new XMLWriter(new OutputStreamWriter(
			// new FileOutputStream("db.xml"),"utf-8"),format);
			writer.write(doc);
			writer.close();

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}



你可能感兴趣的:(dom4j向xml文件中写数据乱码问题解决)