xml 将解析的文件里的值赋给对象,将对象存入集合

xiaoxiao2021-02-27  246

在dom解析的基础上加了很多if语句,不是最优解法.

public class Dom4jaddList { @Test public void DompareXml() throws Exception { File file = new File("src/com/youv/xml/test/students.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); DOMReader reader = new DOMReader(); Document doc = reader.read(builder.parse(file)); // 获取根节点的元素对象 Element node = doc.getRootElement(); List<Student> liststu = new ArrayList<Student>(); // 创建对象 Student student = new Student(); // 在遍历的过程中将元素存入对象中,再存入集合中 listnode(node,student,liststu); // 遍历集合 iter(liststu); } @SuppressWarnings("unchecked") public void listnode(Element node,Student student,List<Student> liststu) { // 获取根元素的名字 // System.out.println("根元素名字是"+node.getName()); // 获取元素的属性信息 List<Attribute> list = node.attributes(); for (Attribute attribute : list) { String id=attribute.getText(); student.setId(id); System.out.println(id); } // 获取文本 if (!(node.getTextTrim().equals(""))) { // 获取文本数据 String str = node.getName(); String data = (String) node.getData(); if (str.equals("name")) { student.setName(data); } if (str.equals("sex")) { student.setSex(data); } if (str.equals("age")) { //xml文件的数据是有顺序的,age是一个student标签的最后一个子标签.所以在这里存入集合 int age = Integer.parseInt(data); student.setAge(age); liststu.add(student); } } Iterator<Element> it = node.elementIterator(); while (it.hasNext()) { Element element = it.next(); //在这里进行判断,因为是递归操作,所以每次迭代都需要将完成一部分的数据重新放入自己的方法 //中.element,student,liststu,需要判断什么时候需要创建新的student对象, if(element.getName().equals("student")){ student=new Student(); listnode(element,student,liststu); }else{ listnode(element,student,liststu); } } } public void iter(List<Student> liststu) { Iterator<Student> it = liststu.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
转载请注明原文地址: https://www.6miu.com/read-7437.html

最新回复(0)