package com.xml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;
public class Test02 {
public static void main(String[] args) throws SAXException, IOException {
//路径及文件名称
String path = "f:"+ File.separator + "t2.xml" ;
//对象
ArrayList<E> es = new ArrayList<E>();
es.add(new E(1,"jack" , 20 , 8888.88)) ;
es.add(new E(2,"mary" , 19 , 9999.88)) ;
es.add(new E(1,"tom" , 20 , 7777.88)) ;
//创建一个文档对象
Document doc = DocumentHelper.createDocument();
//添加根节点
Element root = doc.addElement("List");
//从对象中取出数据,在文档中添加节点和内容信息
for (int i = 0; i < es.size(); i++) {
Element element = root.addElement("E");
element.addAttribute("id", es.get(i).getId()+"");
element.addElement("name").setText(es.get(i).getName());
element.addElement("age").setText(es.get(i).getAge()+"");
element.addElement("salary").setText(es.get(i).getSalary()+"");
}
//格式化输出
OutputFormat format = OutputFormat.createPrettyPrint();
//将输出流有格式的写出到xml文档中
XMLWriter w = new XMLWriter(new FileOutputStream(path) , format);
w.write(doc);
w.close();
}
}
class E implements Serializable{
private static final long serialVersionUID = 1L;
private int id ;
private String name ;
private int age ;
private double salary ;
public E() {
super();
// TODO Auto-generated constructor stub
}
public E(int id, String name, int age, double salary) {
super();
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
E other = (E) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(salary) != Double
.doubleToLongBits(other.salary))
return false;
return true;
}
@Override
public String toString() {
return "E [age=" + age + ", id=" + id + ", name=" + name + ", salary="
+ salary + "]";
}
}
dom4j 创建 并 写入 xml文件
最新推荐文章于 2024-01-04 14:59:08 发布