package com.imooc.learn3;



import java.io.File;

import java.util.Iterator;

import java.util.List;



import org.dom4j.Attribute;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;









public class Dom4JTest {

public static void main(String[] args) throws DocumentException {

//创建一个Reader对象

SAXReader reader=new
SAXReader();

//通过read方法加载文件

Document doc= reader.read(new File("demo/Books.xml"));

//获取根节点

Element bookStore=doc.getRootElement();

//获取迭代器,通过elementIterator

Iterator
itor=bookStore.elementIterator();

//遍历迭代器,获取根节点的信息

while (itor.hasNext()) {

System.out.println("开始遍历某一本书");

Element
book=(Element)itor.next();

//获取book的属性名以及属性值

List<Attribute> atts=book.attributes();


for (Attribute attribute : atts) {

System.out.println("节点名:"+attribute.getName()+"节点值:"+attribute.getValue());

System.out.println();

}



Iterator<Element> boChild=book.elementIterator();


while (boChild.hasNext()) {

Element el=boChild.next();

System.out.println("节点名:"+el.getName()+"节点值:"+el.getStringValue());

}





System.out.println("结束遍历某本书");


}




}



}