1、DOM4J是第三方提供的工具类,使用前需要导入DOM4J的jar包
下载地址:https://dom4j.github.io
public class Dom4jDemo { public static void main(String[] args) throws DocumentException { List<Student> stuList = new ArrayList<>(); // 获取解析器对象 SAXReader sr = new SAXReader(); // 利用解析器对象把xml文件加载到内存并返回文档对象 Document document = sr.read(new File("src\\xml\\student.xml")); // 获取文档的根标签 Element rootElement = document.getRootElement(); // 获取根标签下的子标签student List<Element> studentElements = rootElement.elements("student"); for (Element studenElement : studentElements) { // 获取id这个属性和它的属性值 Attribute attribute = studenElement.attribute("id"); String id = attribute.getValue(); // 获取Student类的属性对应的每个标签以及每个标签的标签体内容 Element element2 = studenElement.element("name"); String name = element2.getText(); Element element3 = studenElement.element("age"); String age = element3.getText(); Element element4 = studenElement.element("height"); String height = element4.getText(); // 将数据封装到student对象 Student s = new Student(); s.setAge(Integer.parseInt(age)); s.setHeight(Integer.parseInt(height)); s.setId(id); s.setName(name); // 将student对象放入集合 stuList.add(s); } // 遍历集合 for (Student stu : stuList) { System.out.println(stu); } } }
public class Student { private String id; private String name; private int age; private int height; public Student() {} public Student(String id, String name, int age, int height) { this.id = id; this.name = name; this.age = age; this.height = height; } 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + ", height=" + height + "]"; } }
<?xml version="1.0" encoding="UTF-8" ?> <students> <student id="1"> <name>张三</name> <age>20</age> <height>180</height> </student> <student id="2"> <name>李四</name> <age>21</age> <height>178</height> </student> </students>
标签:xml,String,DOM4J,age,id,height,解析,public,name From: https://www.cnblogs.com/weiduaini/p/17225751.html