Dom4j生成XML文件

下面是使用Dom4j生成XML的示例:

package com.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Dom4jTest {

	public static void main(String[] args) throws Exception {
		Dom4jTest test = new Dom4jTest();
		Document doc = test.generateDocument2();
		File file = new File("src/com/xml/student.xml");
		test.saveDocument(doc, file);
	}
	public void saveDocument(Document doc,File file) {
		//美化格式,会进行换行
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		//按照字符流将xml输出到指定的file文件中
		OutputStream os;
		try {
			os = new FileOutputStream(file);
			OutputStreamWriter osw = new OutputStreamWriter(os);
			XMLWriter writer = new XMLWriter(osw,format);
			//根据document内容按照xml格式输出
			writer.write(doc);
			writer.flush();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 *  
	 *  
	 *  	...
	 *  
	 * 
	 */
	public Document generateDocument() {
		//创建文档
		Document document = DocumentHelper.createDocument();
		//创建根节点
		Element studentsElement = document.addElement("students");
		//创建注释
		studentsElement.addComment("this is a comment");
		//创建stu1子节点
		Element stu1Element = studentsElement.addElement("student");
		//stu1子节点添加属性
		stu1Element.addAttribute("id", "1");
		Element nameElement = stu1Element.addElement("name");
		nameElement.addText("Tom");
		Element ageElement = stu1Element.addElement("age");
		ageElement.addText("20");
		
		return document;
	}
	
	public Document generateDocument2() {
		String str = ""
				+""
				+ ""
				+""
				+"jack20"
				+ ""
				+"";
		
		Document document = null;
		try {
			document = DocumentHelper.parseText(str);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return document;
	}
}

 

你可能感兴趣的:(个人总结,XML学习笔记)