1. 程式人生 > >【轉載】在Java中使用xpath對xml解析

【轉載】在Java中使用xpath對xml解析

想繞過xpath,其實很簡單,看下面

https://www.cnblogs.com/vastsum/p/5940235.html

 

下面是一個小demo入門很詳細(下面解析的是我用jsoup抓取的html頁面)

//首先在dom4j中如何使用xpath技術匯入xPath支援的jar包。jaxen-1.1-beta-6.jar
//(首先要先導dom4j包,dom4j下載地址:http://www.dom4j.org/dom4j-1.6.1/)。

執行截圖:

原始碼:

package xpath;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
 * 讀取下xml文件,獲得document物件。 本文為xml連載第一篇,以下程式碼可以直接執行,結尾附上原始碼下載地址。
 */
class exmple {
	public static void main(String[] args) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File("./hh6.xml"));

		/**
		 * 節點物件的操作方法
		 */

		// 獲取文件根節點
		Element root = document.getRootElement();
		// 輸出根標籤的名字
		System.out.println(root.getName());

		// 獲取根節點下面的所有子節點(不包過子節點的子節點)
		List<Element> list = root.elements();
		// 遍歷List的方法
		for (Element e : list) {
			System.out.println(e.getName());
		}

		// 獲得指定節點下面的子節點
		Element contactElem = root.element("head");// 首先要知道自己要操作的節點。
		List<Element> contactList = contactElem.elements();
		for (Element e : contactList) {
			System.out.println("999" + e.getName());
		}

		// 呼叫下面獲取子節點的遞迴函式。
		getChildNodes(root);
		System.out.println("子節點輸出完畢");
		// 獲得當前標籤下指定名稱的第一個子標籤
		Element conElem = root.element("head");
		System.out.println(conElem.getName());

		// 獲得更深層次的標籤(一層一層的獲取)
		Element nameElem = root.element("head").element("style");
		System.out.println(nameElem.getName());
	}

	// 遞迴查詢節點函式,輸出節點名稱
	private static void getChildNodes(Element elem) {
		System.out.println(elem.getName()+elem.getPath());//重點:::並輸出dom路徑!!!
		Iterator<Node> it = elem.nodeIterator();
		while (it.hasNext()) {
			Node node = it.next();
			if (node instanceof Element) {
				Element e1 = (Element) node;
				getChildNodes(e1);
			}

		}
	}

}