dm4j 写

package com.jin.demo;

import java.io.FileWriter;
import java.io.IOException;

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

public class TestCreate
{
	public static void main(String[] args) throws Exception
	{
		
		//第一步, 准备向文件写出
		//写出位置
		FileWriter fileWriter = new FileWriter("E:\\JavaProject\\TestDom4j\\lib\\TestCreated.xml");
		//写出的编码
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		//写出xml的流
		XMLWriter writer = new XMLWriter(fileWriter, format);
		
		
		
		
		//第二步,吧要写出的Document和里面的内容组织出来
		Document doc = DocumentHelper.createDocument();
		//先添加根节点元素,然后在根节点下添加元素
		Element root = doc.addElement("学生信息"); 
		
		Element stu = null;
		Element stuId = null;
		Element stuName = null;
		Element stuSex = null;
		Element stuAge = null;
		//添加5条学生信息
		for(int i=1; i<=5; i++)
		{
			//dom4j中不需要先create再add,直接addElment时,就创建了这个Element
			stu = root.addElement("学生");
			stu.addAttribute("sid", "00" + i);
			
			stuId = stu.addElement("编号");
			stuId.setText("00" + i);
			stuName = stu.addElement("姓名");
			stuName.setText("Alshavin" + i);
			stuSex = stu.addElement("性别");
			stuSex.setText("male");
			stuAge = stu.addElement("年龄");
			stuAge.setText(20 + i + "");
		}
		
		
		//第三步,写出 (向文件流里一样的try..catch...finally处理关闭,省略)
		writer.write(doc);
		writer.close();
		
	}
}

你可能感兴趣的:(写)