使用DOM4J动态创建XML文件

package cn.itcast.xml.parser.dom4j;

import java.io.FileOutputStream;
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 Demo4 {
	private static void writerToFile(Document document)throws Exception{
		//取得输出格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		//设置XML输出的编码方式
		format.setEncoding("UTF-8");
		//将内存中的字节转换成字符
		Writer writer = new OutputStreamWriter(new FileOutputStream("src/cn/itcast/xml/parser/dom4j/create.xml"),"UTF-8");
		//创建dom4j的输出字符流
		XMLWriter xmlWriter = new XMLWriter(writer,format);
		//真正输出
		xmlWriter.write(document);
		//关闭流
		xmlWriter.close();
	}
	public static void main(String[] args) throws Exception {
		//创建XML文档对象
		Document document = DocumentHelper.createDocument();
		//创建根元素
		Element rootElement = DocumentHelper.createElement("root");
		rootElement.addElement("name").setText("jack");
		rootElement.element("name").addAttribute("type","大名");
		//将根元素加入到文档对象中来
		document.add(rootElement);
		writerToFile(document);
	}
}












 

你可能感兴趣的:(java,xml)