luvhl 2020-02-14
1、XML文档students.xml
<?xml version="1.0" encoding="UTF-8"?> <students> <student> <name>吴飞</name> <college>java学院</college> <telephone>62354666</telephone> <notes>男,1982年生,硕士,现就读于北京邮电大学</notes> </student> <student> <name>李雪</name> <college>C++学院</college> <telephone>62358888</telephone> <notes>男,1987年生,硕士,现就读于中国农业大学</notes> </student> <student> <name>Jack</name> <college>PHP学院</college> <telephone>66666666</telephone> <notes>我是澳洲人</notes> </student> <student> <name>Lucy</name> <college>Android学院</college> <telephone>88888888</telephone> <notes>我是美国人</notes> </student> </students>
package com.zda.xml; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Dom4jTest { /** * @param args */ public static void main(String[] args) { try { //1、创建解析器 SAXReader reader = new SAXReader(); //2、通过解析器的read方法将配置文件读取到内存中,生成一个Document[org.dom4j]对象树 Document document = reader.read("conf/students.xml"); //3、获取根节点 Element root = document.getRootElement(); //4、开始遍历根节点 for(Iterator<Element> rootIter = root.elementIterator();rootIter.hasNext();){ Element studentElt = rootIter.next(); for(Iterator<Element> innerIter = studentElt.elementIterator();innerIter.hasNext();){ Element innerElt = innerIter.next(); String innerValue = innerElt.getStringValue(); System.out.println(innerValue); } System.out.println("-------------------------------"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }