这篇文章主要介绍了基于Java创建XML(无中文乱码)过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
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(); } }
运行结果: