代码如下:
package com.xml.dom4j;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class dom4jTest {
public static void main(String[] args) throws Exception {
System.out.println("开始解析");
SAXReader reader = new SAXReader();
//加载books.xml
Document document= reader.read( new File("books.xml"));
Element bookstore= document.getRootElement();
//获取一个迭代器对象
Iterator it =bookstore.elementIterator();
while(it.hasNext()){
Element book=(Element)it.next();
List<Attribute> booklist = book.attributes();
for(Attribute b:booklist){
String attrName= b.getName();
String attrValue=b.getValue();
System.out.println("属性名为:"+attrName+" 属性值为:"+attrValue);
Iterator<Attribute> son=book.elementIterator();
while(son.hasNext()){
Element bookson=(Element)son.next();
System.out.println( "节点名为:"+ bookson.getName()+" "
+ "节点值为:"+bookson.getStringValue());
}
}
}
}
}