使用XPATH解析XML文件
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class TestXPath {
public static void main(String[] args) throws DocumentException {
//1 创建SAXReader对象
SAXReader reader = new SAXReader();
//2 读XML文件
Document doc = reader.read("web/book.xml");
//得到第一个author节点
Node node = doc.selectSingleNode("//author");
System.out.println("节点的名称:" + node.getName() + "\t" + node.getText());
//得到所有author节点
List nodeList = doc.selectNodes("//author");
for (Iterator iBook = nodeList.iterator();iBook.hasNext();) {
Node n = iBook.next();
System.out.println("节点的名称:" + n.getName() + "\t" + n.getText());
}
List nameList = doc.selectNodes("//name");
for (Iterator iBook = nameList.iterator();iBook.hasNext();) {
Node n = iBook.next();
System.out.println("节点的名称:" + n.getName() + "\t" + n.getText());
}
}
}
需要准备DOM4J 的 jar 包、Jaxen 的 jar 包。