需要的jar包:dom4j-1.6.1.jar
package com.zhang.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.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Dom4JParser { public static void main(String[] args) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(new File("books.xml")); Element bookStore = document.getRootElement(); Iterator it = bookStore.elementIterator(); while (it.hasNext()) { System.out.println("=====開始遍歷某一本書====="); Element book = (Element) it.next(); 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("=====結束遍歷某一本書====="); } } }