package cn.demo;
import java.io.File;import java.util.ArrayList;import java.util.List;
import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;
import cn.domain.Cls;import cn.domain.Student;
public class StudDao { public Listquery() throws Exception { // 1:创建一个List List clses = new ArrayList ();
// 1:创建XML解析器 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder();
// 2:解析Xml文件,返回一个org.w3c.Docuemnt内存文档对象 Document dom = db.parse(new File("./files/studs.xml")); // 3:读取所有cls元素 NodeList nl = dom.getElementsByTagName("cls"); // 遍历所有List for (int i = 0; i < nl.getLength(); i++) {
// 每一次读取到一个元素,都是一个新的班级 Cls cls = new Cls();
Element ele = (Element) nl.item(i);// 获取每一个元素String name = ele.getAttribute("name");// 获取name属性的值
// 设置名称 cls.setName(name); // 在ele下获取元素 NodeList studs = ele.getElementsByTagName("stud"); for (int j = 0; j < studs.getLength(); j++) {
Student student = new Student();
Element stud = (Element) studs.item(j); String id = stud.getAttribute("id"); String studName = stud.getElementsByTagName("name").item(0).getTextContent(); String studAge = stud.getElementsByTagName("age").item(0).getTextContent(); NodeList tels = stud.getElementsByTagName("tel"); String tel = ""; 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); } return clses; }}package cn.demo;
import java.util.List;
import org.junit.Test;
import cn.domain.Cls;import cn.domain.Student;
public class StudAction { @Test public void test1() throws Exception { Listlist = new StudDao().query(); for(Cls c:list){ System.err.println(c.getName()); for(Student s:c.getStuds()){ System.err.println(" "+s.getName()+","+s.getId()+","+s.getAge()+","+s.getTel()); } System.err.println("-----------------------------"); } }}