/****************************************/
//测试类
import java.io.File;
import java.util.List;
import org.junit.Test;
import entity.Student;
public class Dom4jTest {
@Test
public void test() throws Exception{
// 创建saxReader对象
File xmlFile = new File("C:/Users/zb/Desktop/studentInfo.xml");
List<Student> studentList = XMLUtil.fileTransferList(xmlFile);
for (Student student : studentList) {
System.out.println(student.getName());
}
}
}
/***********************************************/
//工具类
package domFourj;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import entity.Student;
public class XMLUtil {
public static List<Student> fileTransferList(File file) throws DocumentException{
// 返回值:学生信息集合
List<Student> studentList=new ArrayList<Student>();
// 创建saxReader对象
SAXReader reader = new SAXReader();
// 通过read方法读取一个文件 转换成Document对象
Document document = reader.read(file);
//获取根节点元素对象
Element root = document.getRootElement();
// 获取学院节点集合
List<Element> collegeElements = root.elements();
//已知属性名情况下
for (Element college : collegeElements) {
List<Student> collegeStudentList = getStudentListFromCollegeElement(college);
studentList.addAll(collegeStudentList);
}
return studentList;
}
private static List<Student> getStudentListFromCollegeElement(Element collegeElement){
// 返回值:学生信息集合
List<Student> studentList = new ArrayList<Student>();
List<Element> classElements = collegeElement.elements();
for (Element classElement : classElements) {
List<Student> classStudentList = getStudentListFromClassElement(classElement);
studentList.addAll(classStudentList);
}
return studentList;
}
private static List<Student> getStudentListFromClassElement(Element classElement){
// 返回值:学生信息集合
List<Student> studentList = new ArrayList<Student>();
List<Element> studentElements = classElement.elements();
for (Element student : studentElements) {
List<Element> propertyElements = student.elements();
Student student2 = studentElementTransferStudentEntity(propertyElements);
studentList.add(student2);
}
return studentList;
}
private static Student studentElementTransferStudentEntity(List<Element> propertyElements){
Student stu = new Student();
for (Element property : propertyElements) {
String name = property.attributeValue("name");
String value = property.attributeValue("value");
if("name".equals(name)){
stu.setName(value);
}
if("age".equals(name)){
stu.setAge(value);
}
if("garden".equals(name)){
stu.setGarden(value);
}
}
return stu;
}
}
/****************************/
//实现效果
姓名:航三
姓名:李希
姓名:王五
姓名:赵柳
姓名:刘琪
姓名:周扒皮
姓名:赵qq
来源:https://www.cnblogs.com/lixud/p/6137960.html