package com.zyb.xml;
import java.io.File;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class testXml {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//1.创建SAXReader对象用于读取xml文件
SAXReader reader = new SAXReader();
//2.读取xml文件,获得Document对象
Document doc = reader.read(new File("src/book.xml"));
//3.获取根元素
Element root = doc.getRootElement();
//4.获取根元素下的所有子元素(通过迭代器)
Iterator it = root.elementIterator();
while(it.hasNext()){
Element e = it.next();
//获取id属性(attribute是属性的意思)
Attribute id = e.attribute("id");
System.out.println(id.getName()+" = "+id.getStringValue());
Element author = e.element("author");
Element money = e.element("price");
Element time = e.element("time");
System.out.println(author.getName()+" = "+author.getStringValue());
System.out.println(money.getName()+" = "+money.getData());
System.out.println(time.getName()+" = "+time.getText());
System.out.println("---------------------------------------------------------------");
}
}
}
运行结果: