一、基本概念介紹
XPath 是一門在 XML 文檔中查找信息的語言, 可用來在 XML 文檔中對元素和屬性進行遍歷。XPath 是 W3C XSLT 標准的主要元素,並且 XQuery 和 XPointer 同時被構建於 XPath 表達之上。因此,對 XPath 的理解是很多高級 XML 應用的基礎。
XPath非常類似對數據庫操作的SQL語言,或者說JQuery,它可以方便開發者抓起文檔中需要的東西。(dom4j也支持xpath
1.節點類型
XPath中有七種結點類型:元素、屬性、文本、命名空間、處理指令、注釋以及文檔節點(或稱為根節點)。文檔中存在元素節點,屬性節點,根節點
2.常用路徑表達式
表達式 |
描述 |
節點名稱(nodename) | 選取此節點的所有子節點 |
/ | 從根節點選取 |
// | 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置 |
. | 選取當前節點 |
.. | 選取當前節點的父節點 |
@ | 選取屬性 |
示例如下:
//@lang | 選取所有名為 lang 的屬性 |
3.限定語
用來查找某個特定的節點或者包含某個指定的值的節點。以方括號括起
//book[price>35.00] | 選擇所有book 元素,且其中的 price 元素的值須大於 35.00 |
/bookstore/book[1] | 選取屬於 bookstore 子元素的第一個 book 元素。 |
/bookstore/book[last()] | 選取屬於 bookstore 子元素的最后一個 book 元素。 |
/bookstore/book[last()-1] | 選取屬於 bookstore 子元素的倒數第二個 book 元素。 |
/bookstore/book[position()<3] | 選取最前面的兩個屬於 bookstore 元素的子元素的 book 元素。 |
//title[@lang] | 選取所有擁有名為 lang 的屬性的 title 元素。 |
//title[@lang='eng'] | 選取所有 title 元素,且這些元素擁有值為 eng 的 lang 屬性。 |
/bookstore/book[price>35.00] | 選取所有 bookstore 元素的 book 元素,且其中的 price 元素的值須大於 35.00。 |
/bookstore/book[price>35.00]/title | 選取所有 bookstore 元素中的 book 元素的 title 元素,且其中的 price 元素的值須大於 35.00。 |
通配符 | 描述 |
* | 匹配任何元素節點 |
@* | 匹配任何屬性節點 |
node() | 匹配任何類型的節點 |
| | 選取若干路徑 |
使用示例 | |
路徑表達式 | 結果 |
/bookstore/* | 選取 bookstore 元素的所有子節點 |
//* | 選取文檔中的所有元素 |
//title[@*] | 選取所有帶有屬性的 title 元素。 |
//book/title | //book/price | 選取所有 book 元素的 tilte 和 price 元素。 |
//title | //price | 選取所有文檔中的 title 和 price 元素。 |
/bookstore/book/title | //price | 選取所有屬於 bookstore 元素的 book 元素的 title 元素,以及文檔中所有的 price 元素 |
二、代碼示例
import java.io.File;
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XPathDemo {
private static Document doc;
private static XPath xpath;
public static void main(String[] args) throws Exception {
init();
getRootEle();
getChildEles();
getPartEles();
haveChildsEles();
getLevelEles();
getAttrEles();
//打印根節點下的所有元素節點
System.out.println(doc.getDocumentElement().getChildNodes().getLength());
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
System.out.print(nodeList.item(i).getNodeName() + " ");
}
}
}
// 初始化Document、XPath對象
public static void init() throws Exception {
// 創建Document對象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new FileInputStream(new File("demo.xml")));
// 創建XPath對象
XPathFactory factory = XPathFactory.newInstance();
xpath = factory.newXPath();
}
// 獲取根元素
// 表達式可以更換為/*,/rss
public static void getRootEle() throws XPathExpressionException {
Node node = (Node) xpath.evaluate("/rss", doc, XPathConstants.NODE);
System.out.println(node.getNodeName() + "--------"
+ node.getNodeValue());
}
// 獲取子元素並打印
public static void getChildEles() throws XPathExpressionException {
NodeList nodeList = (NodeList) xpath.evaluate("/rss/channel/*", doc,
XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.print(nodeList.item(i).getNodeName() + " ");
}
System.out.println();
}
// 獲取部分元素
// 只獲取元素名稱為title的元素
public static void getPartEles() throws XPathExpressionException {
NodeList nodeList = (NodeList) xpath.evaluate("//*[name() = 'title']",
doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.print(nodeList.item(i).getNodeName() + "-->"
+ nodeList.item(i).getTextContent());
}
System.out.println();
}
// 獲取包含子節點的元素
public static void haveChildsEles() throws XPathExpressionException {
NodeList nodeList = (NodeList) xpath.evaluate("//*[*]", doc,
XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.print(nodeList.item(i).getNodeName() + " ");
}
System.out.println();
}
// 獲取指定層級的元素
public static void getLevelEles() throws XPathExpressionException {
NodeList nodeList = (NodeList) xpath.evaluate("/*/*/*/*", doc,
XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.print(nodeList.item(i).getNodeName() + "-->"
+ nodeList.item(i).getTextContent() + " ");
}
System.out.println("-----------------------------");
}
// 獲取指定屬性的元素
// 獲取所有大於指定價格的書箱
public static void getAttrEles() throws XPathExpressionException {
NodeList nodeList = (NodeList) xpath.evaluate("//bookstore/book[price>35.00]/title", doc,
XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.print(nodeList.item(i).getNodeName() + "-->"
+ nodeList.item(i).getTextContent() + " ");
}
System.out.println();
}
}
使用的XML文檔
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Java Tutorials and Examples 2</title>
<language>en-us</language>
<item>
<title><![CDATA[Java Tutorials 2]]></title>
<link>http://www.javacodegeeks.com/</link>
</item>
<item>
<title><![CDATA[Java Examples 2]]></title>
<link>http://examples.javacodegeeks.com/</link>
</item>
</channel>
<college name="c1">
<class name="class1">
<student name="stu1" sex='male' age="21" />
<student name="stu2" sex='female' age="20" />
<student name="stu3" sex='female' age="20" />
</class>
</college>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
</rss>
三、參考
http://www.w3school.com.cn/xpath/index.asp