package xml;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
* @author xingsir
* 使用DOM4J生成XML文档
*/
public class WriteXmlDemo {
public static void main(String[] args) {
List<Dept> deptlist=new ArrayList<>();
deptlist.add(new Dept(1,"综合部","2020-01-01",400,"孙悟空"));
deptlist.add(new Dept(2,"人事部","2020-01-01",400,"朱悟能"));
deptlist.add(new Dept(3,"研发部","2020-01-01",400,"白龙马"));
deptlist.add(new Dept(4,"销售部","2020-01-01",400,"沙悟净"));
deptlist.add(new Dept(5,"售后部,","2020-01-01",400,"孙悟空"));
try {
Document doc=DocumentHelper.createDocument();
Element root= doc.addElement("list");
for(Dept d : deptlist) {
//向根元素中追加一个<dept>标签
Element empEle = root.addElement("dept");
//追加部门名称
//1 向<dept>标签中追加<name>子标签
Element nameEle = empEle.addElement("name");
//2 向<name>子标签中追加文本信息
nameEle.addText(d.getName());
//追加创建时间
Element creattime= empEle.addElement("creattime");
creattime.addText(d.getCreatetime());
//追加年龄
Element ageEle = empEle.addElement("age");
ageEle.addText(d.getAge()+"");
//追加部长
empEle.addElement("minister").addText(d.getMinister());
//追加一个属性:id="xx"
empEle.addAttribute("id", d.getId()+"");
}
/*
* 将Document对象通过XMLWriter写出以形成 XML文档。
*/
XMLWriter writer = new XMLWriter(
new FileOutputStream("mydept.xml"),
OutputFormat.createPrettyPrint()
);
/*
* 将Document对象通过XMLWriter写出以形成XML文档。
*/
writer.write(doc);
System.out.println("写出完毕!");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}