通过Java创建XML(中文乱码已解决)

时间:2021-11-06 11:39:06
package com.zyb.xml;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer; import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter; public class TestXml2 { public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Document doc = DocumentHelper.createDocument();
//1.创建根节点
Element root = doc.addElement("books");
for(int i=0;i<2;i++){
//2.为根节点添加元素
Element book = root.addElement("book");
//3.如果有属性进行添加
book.addAttribute("id", "001");
//4.为元素继续添加元素
Element author = book.addElement("author");
Element price = book.addElement("price");
Element time = book.addElement("time");
//5.给对应元素赋值
author.addText("亚历山大");
price.addText("12.25");
time.addText("2015-09-05");
} //良好的输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
//6.//创建一个xml文件
OutputStream out = new FileOutputStream("src/book2.xml");
Writer wr = new OutputStreamWriter(out, "UTF-8");//用可改变编码的OutputStreamWriter代替了普通的FileWriter解决中文乱码问题
XMLWriter output = new XMLWriter(wr,format);
//7.将doc输出到xml文件中
output.write(doc);
//8.关闭资源
wr.close();
out.close();
output.close();
} }

  

通过Java创建XML(中文乱码已解决)

运行结果:

通过Java创建XML(中文乱码已解决)