官網下載Dom4j地址:https://dom4j.github.io/ 註意:使用Dom4j開發,需下載dom4j相應的jar文件 題目:後臺利用dom4j解析student.xml文件,並返回List<Student>集合 需要解析的XML: java解析xml代碼: 實體類: /** * @a ...
官網下載Dom4j地址:https://dom4j.github.io/
註意:使用Dom4j開發,需下載dom4j相應的jar文件
題目:後臺利用dom4j解析student.xml文件,並返回List<Student>集合
需要解析的XML:
<?xml version="1.0" encoding="UTF-8"?> <classes> <class name="ST01"> <student id="10001">user1</student> <student id="10002">user2</student> <student id="10003">user3</student> </class> <class name="ST02"> <student id="10004">user4</student> <student id="10005">user5</student> <student id="10006">user6</student> </class> <class name="ST03"> <student id="10007">user7</student> <student id="10008">user8</student> <student id="10009">user9</student> </class> <class name="ST04"> <student id="10010">user10</student> <student id="10011">user12</student> <student id="10012">user13</student> </class> <class name="ST05"> <student id="10013">user14</student> <student id="10014">user15</student> <student id="10015">user16</student> </class> </classes>
java解析xml代碼:
/** * @author hh */ public class XmlUtil { /** * 讀取xml學生列表信息 * @return */ public List<Student> listStudent(){ //創建SAXReader對象 SAXReader reader=new SAXReader(); Document document = null; try { //通過read方法讀取一個文件 轉換成Document對象 document = reader.read(new File("/Users/mac/Documents/students.xml")); } catch (DocumentException e) { e.printStackTrace(); } //獲取根節點元素對象 Element node = document.getRootElement(); return elementMethod(node); } /** * 獲取節點中的信息 * @param node * @return */ private List<Student> elementMethod(Element node){ List<Student> list = new ArrayList<Student>(); //獲取所有class 節點 List<Element> elementClass = node.elements("class"); for (Element aClass : elementClass) { //獲取所有student節點 List<Element> elelmentStu=aClass.elements("student"); for (Element element : elelmentStu) { //創建學生對象 Student stu = new Student(); //class節點里name的值 stu.setSclazz(aClass.attribute("name").getValue()); //student節點里ID的值 stu.setSid(element.attribute("id").getValue()); //student節點里的String值 stu.setSname(element.getStringValue()); list.add(stu); } } return list; } }
實體類:
/** * @author hh */ public class Student { private String sname; private String sid; private String sclazz; public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getSclazz() { return sclazz; } public void setSclazz(String sclazz) { this.sclazz = sclazz; } @Override public String toString() { return "Student{" + "sname='" + sname + '\'' + ", sid='" + sid + '\'' + ", sclazz='" + sclazz + '\'' + '}'; } }View Code
@Test 代碼:
public class StudentDaoTest { @Test public void testlistStudent(){ List<Student> list = new XmlUtil().listStudent(); for (Student student : list) { System.out.println(student); } } }View Code
運行結果: