首先咱們要先有dom4j的jar包,沒有的能夠去https://dom4j.github.io/下載java
建立一個web項目,並在WEB-INF文件下建立一個lib文件夾,把咱們下載的dom4j-1.6.1jar包放到裏面git
找到File-->Project Structure-->Modules裏的Dependencies,找到咱們項目的lib文件夾github
如今咱們正式開始咱們的項目代碼web
實體類:dom
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文件的格式):ide
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 }
測試:this
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 }
結果:spa