现在的位置: 首页 > 综合 > 正文

用dom4j创建xml(中文不会乱码)

2013年09月09日 ⁄ 综合 ⁄ 共 1331字 ⁄ 字号 评论关闭

package com.dom4j;

import java
.io.FileOutputStream;
import java
.io.FileWriter;
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;

import com.po.StudentBean;

/*
 * 利用dom4j生成xml文件

 * */
public class CreateXML {
//传入学生类的bean
public void CreateXMl(StudentBean sn){
//创建document对象
Document document = DocumentHelper.createDocument();
//定义根节点Element
Element rootGen = document.addElement("root");
//定义根节点ROOT的子节点们
Element nameGen = rootGen.addElement("Name");
nameGen.addAttribute("name", "我是中文");
Element ageGen = rootGen.addElement("Age");
Element addrGen = rootGen.addElement("Address");
Writer writer = null;
OutputFormat format = null;
XMLWriter xmlwriter = null;
//将定义好的内容写入xml文件

try {
// writer = new FileWriter("d:/test.xml");
// writer = new FileOutputStream("d:/test.xml");
//进行格式化
format = OutputFormat.createPrettyPrint();
//设定编码
format.setEncoding("UTF-8");
xmlwriter = new XMLWriter(new FileOutputStream("d:/test.xml"), format);
xmlwriter.write(document);
xmlwriter.flush();
xmlwriter.close();
System.out.println("-----------Xmlfile successfully created-------------");
} catch (Exception e) {
e.printStackTrace();
System.out.println("-----------Exception occured during of create xmlfile -------");
}
}
public static void main(String[] args) {
CreateXML cx = new CreateXML();
StudentBean sn = new StudentBean();
cx.CreateXMl(sn);
}
}

抱歉!评论已关闭.