用idea完成一个dom4j实例
首先我们要先有dom4j的jar包,没有的可以去https://dom4j.github.io/下载
创建一个web项目,并在WEB-INF文件下创建一个lib文件夹,把我们下载的dom4j-1.6.1jar包放到里面
找到File-->Project Structure-->Modules里的Dependencies,找到我们项目的lib文件夹
现在我们正式开始我们的项目代码
实体类:
1 package vo;
2
3 public class Student {
4 private String name;//姓名
5 private int age; //年龄
6
7 public Student() {
8 }
9
10 public Student(String name, int age) {
11 this.name = name;
12 this.age = age;
13 }
14
15 public String getName() {
16 return name;
17 }
18
19 public void setName(String name) {
20 this.name = name;
21 }
22
23 public int getAge() {
24 return age;
25 }
26
27 public void setAge(int age) {
28 this.age = age;
29 }
30
31 //重写toSting()方法
32 @Override
33 public String toString() {
34 return "Student{" +
35 "name='" + name + '\'' +
36 ", age=" + age +
37 '}';
38 }
39 }
xml文件(注意xml文件的格式):
1 <?xml version="1.0" encoding="UTF-8"?>
2 <students>
3
4 <student>
5 <name>张三</name>
6 <age>39</age>
7 </student>
8
9 <student>
10 <name>李四</name>
11 <age>45</age>
12 </student>
13
14 <student>
15 <name>王五</name>
16 <age>34</age>
17 </student>
18 </students>
测试方法:
1 package dao;
2
3 import org.dom4j.Document;
4 import org.dom4j.DocumentException;
5 import org.dom4j.Element;
6 import org.dom4j.io.SAXReader;
7 import vo.Student;
8
9 import java.io.File;
10 import java.util.ArrayList;
11 import java.util.List;
12
13 public class StudentDao {
14 public List<Student> getStudentAll() throws DocumentException {
15 //创建SAXReader对象
16 SAXReader saxReader = new SAXReader();
17 //找到定义的xml文件,把里面的内容变成Document对象
18 Document document = saxReader.read(new File("src/xml/studentXml.xml"));
19 //获取根节点元素对象
20 Element root = document.getRootElement();
21 //把所有元素节点放入到List中
22 List<Element> listElement = root.elements();
23
24 List<Student> listBook = new ArrayList<Student>();
25 Student student = null;
26 //遍历所有的元素节点
27 for (Element e : listElement) {
28 //把节点为name里的数取出
29 String name = e.element("name").getText();
30 //把节点为age里的数取出
31 int age = Integer.parseInt(e.element("age").getText());
32 //把取到的数加入到Student对象中
33 student=new Student(name,age);
34 //把Student对象加入到List集合里
35 listBook.add(student);
36 }
37 return listBook;
38 }
39 }
测试:
1 package main;
2
3 import dao.StudentDao;
4 import org.dom4j.DocumentException;
5
6 public class StudentTest {
7 public static void main(String[] args) throws DocumentException {
8 StudentDao dao=new StudentDao();
9 System.out.println(dao.getStudentAll());
10 }
11 }
结果: