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> 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文件内容如下:


进行操作如截图


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

解决办法:

设置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();
		}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值