java中利用dom4j解析XML文件
程序员文章站
2022-07-02 13:46:18
官网下载Dom4j地址:https://dom4j.github.io/ 注意:使用Dom4j开发,需下载dom4j相应的jar文件 题目:后台利用dom4j解析student.xml文件,并返回List集合 需要解析的XML: java解析xml代码: 实体类: /** * @a ......
官网下载dom4j地址:
注意:使用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 + '\'' + '}'; } }
@test 代码:
public class studentdaotest { @test public void testliststudent(){ list<student> list = new xmlutil().liststudent(); for (student student : list) { system.out.println(student); } } }
运行结果:
上一篇: solr7.2.0定时全量和增量更新
下一篇: Java原子类中CAS的底层实现