(1)导入DOM4J的JAR包
(2)xml文件内容
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author>乔治·马丁</author>
<year>2015</year>
<price>200</price>
</book>
<book id="2">
<name>光荣与梦想</name>
<year>2004</year>
<price>150</price>
<publish>科学出版社</publish>
</book>
</bookstore>
(3)JAVA解析方法
package com.myjavapractice.xml;
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) {
//创建一个SAXReader对象
SAXReader reader = new SAXReader();
try {
//通过SAXReader对象的read方法获得一个Document对象
Document document = reader.read(new File("src/res/MyFirstXML.xml"));
//通过Document对象获取根节点
Element bookStore = document.getRootElement();
//通过Element对象的elementIterator方法获取子节点的迭代器
Iterator iterator = bookStore.elementIterator();
//遍历迭代器,获取子节点的内容
while(iterator.hasNext()){
System.out.println("**********开始遍历**********");
//获取子节点的属性列表
Element book = (Element)iterator.next();
List<Attribute> bookAttr = book.attributes();
//遍历属性列表,输出属性名称和值
for(Attribute attr : bookAttr){
String name = attr.getName();
String value = attr.getValue();
System.out.println("属性名称是: "+name+"--->属性值是:"+value);
}
//遍历book子节点
Iterator Iterator2 = book.elementIterator();
while(Iterator2.hasNext()){
Element bookChild = (Element)Iterator2.next();
String name2 = bookChild.getName();
String value2 = bookChild.getStringValue();
System.out.println("节点名是: "+ name2+"--->节点值是:"+value2);
}
System.out.println("**********结束遍历**********");
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}