天天看點

使用xPath來讀取xml檔案

使用xPath來讀取xml檔案
使用xPath來讀取xml檔案
使用xPath來讀取xml檔案
使用xPath來讀取xml檔案

 四、XPath  語言

XPath 是一種用于在 XML 中查找資訊語言。XPath 可用來在 XML 文檔中對元素和屬性進行周遊。

4.1 XPath 基本介紹

1)XPath 使用路徑表達式在 XML 文檔中進行導航。

2)XPath 包含一個标準函數庫。

3)XPath 是 XSLT 中的主要元素。

4)XPath 是一個 W3C 标準。

4.2 使用 XPath 的好處

當我們單純使用 DOM 定位節點時,大部分時間需要一層一層的處理,如果有了 XPath,我們定位節點

将變得很輕松,它可以根據路徑、屬性,甚至是條件進行節點的檢索。

4.3 XPath 基本文法

XPath 的常見規則:

1)從根節點開始查找,如:/bookshelf/book,即從根标記下查找所有的 book 标記。

2)查找某個節點,不管其位置,如://book,即忽略位置,查找所有 book 标記。

3)@選擇屬性,如://@ID,即擷取指定名稱的屬性,擷取屬性名為 ID 的屬性,同樣擷取所有的 ID 屬

性。

4)[index]根據索引選擇節點,如:/bookshelf/book[1],即擷取根标記下第一個 book 标記。

 注意事項:索引從 1 開始!

5)根據屬性選取節點,如:/bookshelf/book[@ID='1234'],即擷取根标記下所有屬性 ID 為 1234 的 book

标記。

6)根據子元素的值擷取節點,如:/bookshelf/book[student='金三順']即擷取根标記下 book 标記的子标

記 student 的值為“金三順”的 book 标記。

xpath文法http://www.w3school.com.cn/xpath/xpath_syntax.asp

xpath其實就是以路徑的形式進行篩選

使用XPath需要新添加包,不然會報錯 xpath它是dom4j支援的但不是必須的.

<!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
<dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.4</version>
</dependency>

<dependency>
    <groupId>org.dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>2.1.0</version>
</dependency>
           
package day12;

import java.io.FileInputStream;
import java.util.List;

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

/**
 * 使用XPath檢索XML資料
 * @author Administrator
 *
 */
public class XPathDemo {
	public static void main(String[] args) {
		try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read(new FileInputStream("myemp.xml"));
			/*
			 * Document支援使用xpath檢索資料
			 * 前提是必須引入jaxen這個jar包 
			 */
			String xpath = "/list/emp[gender='男']/age";
			List<Node> list = doc.selectNodes(xpath);
			
			for(Node ele:list) {
				System.out.println(ele.getName()+":"+ele.getText());
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
           
xml
上一篇: js操作xml
下一篇: jdom 操作xml