java----dom4j 解析XML
dom4j:
由于内部采用迭代器,适合读取大文档;
数据块
1、下载
https://dom4j.github.io/
2、添加包到工程目录下
使用
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Demo{ public static void main(String[] args) throws IOException, DocumentException { DOM4jtest(); } private static void DOM4jtest() throws DocumentException { //创建DOM4的解析器 SAXReader saxReader = new SAXReader(); InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("com\\first\\person.xml"); //DOM4j的dom树 Document read = saxReader.read(resourceAsStream); //获取根节点 Element rootElement = read.getRootElement(); ArrayList<Person> person_List = new ArrayList<>(); Iterator<org.dom4j.Element> iterator = rootElement.elementIterator(); Person person = null; while (iterator.hasNext()){ person = new Person(); Element children = iterator.next(); String p_id = children.attributeValue("person_id"); person.setId(p_id); Iterator<org.dom4j.Element> next_iterator = children.elementIterator(); while (next_iterator.hasNext()){ Element next_children = next_iterator.next(); if ("name".equals(next_children.getName())){ String name = next_children.getText(); person.setName(name); }else if("age".equals(next_children.getName())){ String age = next_children.getText(); person.setAge(age); } } person_List.add(person); } person_List.forEach((p)-> System.out.println(p)); } } class Person{ private String name; private String age; private String id; public void setName(String name) { this.name = name; } public void setAge(String age) { this.age = age; } public void setId(String id) { this.id = id; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", id='" + id + '\'' + '}'; } }