本文先使用DOM4J方式写一个简单地小例子,亲测可以运行,然后在末尾分析其优缺点。
1.准备
<?xml version="1.0" encoding="UTF-8"?>
<student_info>
<student id="1">
<name>张三</name>
<gender>男</gender>
<age>16</age>
</student>
<student id="2">
<name>李四</name>
<gender>女</gender>
<age>15</age>
</student>
</student_info>
- 由于是Maven工程,所有xml都存放在src/main/resources下面
- 引入dom4j的jar包到pom.xml
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
2.编码
- Bean文件:StudentBean.java
public class StudentBean {
private String id;
private String name;
private String gender;
private Integer age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "StudentBean [id=" + id + ",name=" + name + ",gender=" + gender + ",age=" + age + "]";
}
}
- XML读写类:Dom4jTest.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
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.SAXReader;
import org.dom4j.io.XMLWriter;
import bean.StudentBean;
public class Dom4jTest {
// 创建一个Vector来保存每个student对象
public static Vector<StudentBean> studentsVector = new Vector<StudentBean>();
public static void main(String[] args) {
// 创建一个Vector来存放StudentBean对象
Vector<StudentBean> v = readXMLFile("src/main/resources/student.xml");
Iterator<StudentBean> it = v.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
writeXMLFile("src/main/resources/dom4j.xml");
updateXMLFile("src/main/resources/student.xml");
}
// 从XML文件中读数据
public static Vector<StudentBean> readXMLFile(String fileName) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(fileName);
// 获取根节点
Element root = document.getRootElement();
List<Element> students = root.elements("student");
System.out.println("XML文件中有" + students.size() + "个对象!");
for (int i = 0; i < students.size(); i++) {
// 创建一的StudentBean对象用来保存XML中学生的属性
StudentBean sb = new StudentBean();
// 获取student节点的属性值赋给Bean对象
Element element = (Element) students.get(i);
sb.setId(element.attributeValue("id"));
sb.setName(element.elementText("name"));
sb.setGender(element.elementText("gender"));
sb.setAge(Integer.parseInt(element.elementText("age")));
studentsVector.add(sb);
}
} catch (DocumentException e) {
e.printStackTrace();
}
return studentsVector;
}
// 将数据写入XML文件
public static void writeXMLFile(String fileName) {
Document doc = DocumentHelper.createDocument();
// 增加根节点
Element books = doc.addElement("books");
// 增加子元素book1
Element book1 = books.addElement("book");
Element title1 = book1.addElement("title");
Element author1 = book1.addElement("author");
// 为子节点book1添加属性
book1.addAttribute("id","001");
// 为子节点book1添加内容
title1.setText("Harry Potter");
author1.setText("J K. Rowling");
// 增加子元素book2
Element book2 = books.addElement("book");
Element title2 = book2.addElement("title");
Element author2 = book2.addElement("author");
book2.addAttribute("id","002");
title2.setText("Learning XML");
author2.setText("Erik T. Ray");
// 实例化输出格式对象
OutputFormat format = OutputFormat.createPrettyPrint();
// 设置输出编码
format.setEncoding("UTF-8");
// 创建需要写入的File对象
File file = new File(fileName);
// 生成XMLWriter对象,构造函数中的参数为需要输出的文件流和格式
XMLWriter writer;
try {
writer = new XMLWriter(new FileOutputStream(file),format);
// 开始写入,write方法中包含上面创建的Document对象
writer.write(doc);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("数据已经写入XML文档!");
}
// 修改XML文件中的某项内容
public static void updateXMLFile(String fileName) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(fileName);
// 获取根节点
Element students = document.getRootElement();
// 增加一个student
Element student0 = students.addElement("student").addAttribute("id","12");
student0.addElement("name").addText("linri");
student0.addElement("gender").addText("male");
Element student = (Element) students.elements().get(0);
student.addElement("city").addText("Shanghai");
student.remove(student.element("gender"));
student.element("name").addText("mason");
student.element("age").setText("22");
// 实例化输出格式对象
OutputFormat format = OutputFormat.createPrettyPrint();
// 设置输出编码
format.setEncoding("UTF-8");
// 创建需要写入的File对象
File file = new File(fileName);
// 生成XMLWriter对象,构造函数中的参数为需要输出的文件流和格式
XMLWriter writer;
try {
writer = new XMLWriter(new FileOutputStream(file),format);
// 开始写入,write方法中包含上面创建的Document对象
writer.write(document);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (DocumentException e) {
e.printStackTrace();
}
System.out.println("XML文档数据已经修改!");
}
}
3.运行结果
程序自行新建的XML文件dom4j.xml为:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="001">
<title>Harry Potter</title>
<author>J K. Rowling</author>
</book>
<book id="002">
<title>Learning XML</title>
<author>Erik T. Ray</author>
</book>
</books>
程序修改后的student.xml为:
<?xml version="1.0" encoding="UTF-8"?>
<student_info>
<student id="1">
<name>张三mason</name>
<age>22</age>
<city>Shanghai</city>
</student>
<student id="2">
<name>李四</name>
<gender>女</gender>
<age>15</age>
</student>
<student id="12">
<name>linri</name>
<gender>male</gender>
</student>
</student_info>
4.结束
简单易用,采用Java集合框架,并完全支持DOM、SAX和JAXP。
优点:
缺点:
- 大量使用了接口,API较为复杂。
参考:
Dom4j的使用(全而好的文章)