package com;
import java.io.File;
import java.util.BitSet;
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 DOM4J {
private static int number = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
//解析books.xml
//创建SAXReader的对象的reader
SAXReader reader = new SAXReader();
//通过读取reader对象的reader方法加载books.xml
try {
Document document = reader.read(new File("src/res/books.xml"));
//通过Document对象获取根节点bookStorre
Element bookStore = document.getRootElement();
//通过Element方法获取迭代器
Iterator<Element> it = bookStore.elementIterator();
//遍历迭代器获取根节点中的信息
while(it.hasNext()){
number++;
System.out.println("======开始遍历第"+ number +"本书======");
Element book = (Element) it.next();
//获取book的属性名和值
List<Attribute> bookAttrs = book.attributes();
for(Attribute attr : bookAttrs){
System.out.println("节点名 : " + attr.getName() + "----属性值 : " + attr.getValue());
}
Iterator itt = book.elementIterator();
while(itt.hasNext()){
Element bookChild = (Element) itt.next();
System.out.println("节点名是: " + bookChild.getName() + "----节点值 : " + bookChild.getStringValue());
}
System.out.println("======结束遍历第"+ number +"本书======");
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}