xml2
发布时间:2020-12-16 05:41:57 所属栏目:百科 来源:网络整理
导读:packagecn.demo; importjava.io.File;importjava.util.ArrayList;importjava.util.List; importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory; importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.d
packagecn.demo; importjava.io.File; importjava.util.ArrayList; importjava.util.List; importjavax.xml.parsers.DocumentBuilder; importjavax.xml.parsers.DocumentBuilderFactory; importorg.w3c.dom.Document; importorg.w3c.dom.Element; importorg.w3c.dom.NodeList; importcn.domain.Cls; importcn.domain.Student; publicclassStudDao{ publicList<Cls>query()throwsException{ //1:创建一个List List<Cls>clses=newArrayList<Cls>(); //1:创建XML解析器 DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance(); DocumentBuilderdb=dbf.newDocumentBuilder(); //2:解析Xml文件,返回一个org.w3c.Docuemnt内存文档对象 Documentdom=db.parse(newFile("./files/studs.xml")); //3:读取所有cls元素 NodeListnl=dom.getElementsByTagName("cls"); //遍历所有List for(inti=0;i<nl.getLength();i++){ //每一次读取到一个<cls>元素,都是一个新的班级 Clscls=newCls(); Elementele=(Element)nl.item(i);//获取每一个元素<cls> Stringname=ele.getAttribute("name");//获取name属性的值 //设置名称 cls.setName(name); //在ele下获取<stud>元素 NodeListstuds=ele.getElementsByTagName("stud"); for(intj=0;j<studs.getLength();j++){ Studentstudent=newStudent(); Elementstud=(Element)studs.item(j); Stringid=stud.getAttribute("id"); StringstudName=stud.getElementsByTagName("name").item(0).getTextContent(); StringstudAge=stud.getElementsByTagName("age").item(0).getTextContent(); NodeListtels=stud.getElementsByTagName("tel"); Stringtel=""; if(tels.getLength()>0){ tel=tels.item(0).getTextContent(); } student.setName(studName); student.setId(id); student.setAge(Integer.valueOf(studAge)); student.setTel(tel); //放到cls cls.getStuds().add(student); } //放到 clses.add(cls); } returnclses; } }packagecn.demo; importjava.util.List; importorg.junit.Test; importcn.domain.Cls; importcn.domain.Student; publicclassStudAction{ @Test publicvoidtest1()throwsException{ List<Cls>list=newStudDao().query(); for(Clsc:list){ System.err.println(c.getName()); for(Students:c.getStuds()){ System.err.println(""+s.getName()+","+s.getId()+","+s.getAge()+","+s.getTel()); } System.err.println("-----------------------------"); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |