解析XML并将信息封装到对象中
【person.xml】要解析的内容
<?xml version="1.0" encoding="UTF-8"?> <students> <student id="88888" phone="15888888888" sex="男"> <name>张三</name> <age>18</age> <school>清华</school> </student> <student id="99999" phone="15999999999" sex="女"> <name>李四</name> <age>28</age> <school>北大</school> </student> <AAAA> <aa1>aa111</aa1> <aa2>aa222</aa2> </AAAA> <BBBB></BBBB> </students>
【Student.java】xml信息所要封装的Studnet对象
package com.Higgin.parse; public class Student { private String id; private String phone; private String sex; private String name; private String age; private String school; //忽略get/set方法 @Override public String toString() { return "Student [id=" + id + ", phone=" + phone + ", sex=" + sex + ", name=" + name + ", age=" + age + ", school=" + school + "]"; } }
【DemoStudent.java】将xml信息封装到Student对象
package com.Higgin.parse; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; //解析person.xml中student数据,持久化到Student对象中 public class DemoStudent { public static void main(String[] args) throws DocumentException { List<Student> list=new ArrayList<>(); //读取xml,封装对象 SAXReader saxReader =new SAXReader(); Document doc=saxReader.read(new File("./src/person.xml")); //读取Iterator标签 Iterator<Element> it=doc.getRootElement().elementIterator("student"); while(it.hasNext()){ Element elem=it.next(); Student student=new Student(); student.setId(elem.attributeValue("id")); //读取属性 student.setPhone(elem.attributeValue("phone")); student.setSex(elem.attributeValue("sex")); student.setName(elem.elementText("name")); //读取文本 student.setAge(elem.elementText("age")); student.setSchool(elem.elementText("school")); list.add(student); } for(Student student : list){ System.out.println(student.toString()); } } }
【运行结果】