xml解析-dom4j方式
-
项目中新增一个dom4j的依赖
<dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
-
新增一个xml文件
<students> <student> <sid>1</sid> <name>huhoujun</name> <addr>xian</addr> </student> <student> <sid>2</sid> <name>lishushu</name> <addr>beijing</addr> </student> <student> <sid>3</sid> <name>chenggang</name> <addr>shenzhen</addr> </student> <student> <sid>4</sid> <name>liaozizhong</name> <addr>guangzhou</addr> </student> <student> <sid>5</sid> <name>dengweida</name> <addr>guangzhou</addr> </student> <student> <sid>6</sid> <name>xiaodechao</name> <addr>dalian</addr> </student> </students>
-
Student.java
package com.qfedu.pojo; import lombok.Data; @Data public class Student { private int sid; private String name; private String addr; }
-
TestStudentXMLDom4j.java
package com.qfedu.service; import com.qfedu.pojo.Student; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class TestStudentXMLDom4j { public List<Student> parseXml(String xmlFile){ List<Student> list = new ArrayList<>(); // 1. 创建SAXReader对象 SAXReader reader = new SAXReader(); try { // 2. 使用SAXReader对象读取给定的xml文件得到一个Document对象 Document document = reader.read(xmlFile); // 3. 通过Document对象的getRootElement()方法得到xml的跟节点元素 Element root = document.getRootElement(); //System.out.println(size()); // 4. 通过root("根元素")顺藤摸瓜找到所有的子元素节点 List<Element> elements = root.elements(); Student stu = null; for (Element el : elements) { List<Element> list2 = el.elements(); //System.out.println(list2); stu = new Student(); for (Element e : list2) { switch (e.getName()){ case "sid": String ssid = e.getText(); int sid = ssid == null ? 0 : Integer.parseInt(ssid); stu.setSid(sid); break; case "name": String name = e.getText(); stu.setName(name); break; case "addr": String addr = e.getText(); stu.setAddr(addr); break; } } list.add(stu); } } catch (DocumentException e) { e.printStackTrace(); } return list; } @Test public void testParseXml(){ System.out.println(parseXml("stus.xml")); } }
-
运行结果
[Student(sid=1, name=huhoujun, addr=xian), Student(sid=2, name=lishushu, addr=beijing), Student(sid=3, name=chenggang, addr=shenzhen), Student(sid=4, name=liaozizhong, addr=guangzhou), Student(sid=5, name=dengweida, addr=guangzhou), Student(sid=6, name=xiaodechao, addr=dalian)]