深入XPath的詳解以及Java示例代碼分析
更新時(shí)間:2013年06月04日 11:44:43 作者:
本篇文章是對(duì)XPath進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
復(fù)制代碼 代碼如下:
import java.io.IOException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class XpathTest {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("C:/Users/Administrator/Desktop/test.xml");
System.out.println(doc.getChildNodes().getLength());
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
XPathExpression expr = xpath
.compile("http://name/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}
一、結(jié)點(diǎn)類(lèi)型
XPath中有七種結(jié)點(diǎn)類(lèi)型:元素、屬性、文本、命名空間、處理指令、注釋以及文檔節(jié)點(diǎn)(或成為根節(jié)點(diǎn))。 文檔的根節(jié)點(diǎn)即是文檔結(jié)點(diǎn);對(duì)應(yīng)屬性有屬性結(jié)點(diǎn),元素有元素結(jié)點(diǎn)。
二、常用路徑表達(dá)式
表達(dá)式 描述
nodename 選取此節(jié)點(diǎn)的所有子節(jié)點(diǎn)
/ 從根節(jié)點(diǎn)選取
// 從匹配選擇的當(dāng)前節(jié)點(diǎn)選擇文檔中的節(jié)點(diǎn),而不考慮它們的位置
. 選取當(dāng)前節(jié)點(diǎn)
.. 選取當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn)
@ 選取屬性
例如有文檔:
復(fù)制代碼 代碼如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<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>
則:
路徑表達(dá)式 結(jié)果
bookstore 選取 bookstore 元素的所有子節(jié)點(diǎn)
/bookstore 選取根元素 bookstore 注釋?zhuān)杭偃缏窂狡鹗加谡备? / ),則此路徑始終代表到某元素的絕對(duì)路徑!
bookstore/book 選取所有屬于 bookstore 的子元素的 book 元素。
//book 選取所有 book 子元素,而不管它們?cè)谖臋n中的位置。
bookstore//book 選擇所有屬于 bookstore 元素的后代的 book 元素,而不管它們位于 bookstore 之下的什么位置。
//@lang 選取所有名為 lang 的屬性。
三、限定語(yǔ)
用來(lái)查找某個(gè)特定的節(jié)點(diǎn)或者包含某個(gè)指定的值的節(jié)點(diǎn)。以方括號(hào)括起。
例如:
路徑表達(dá)式 結(jié)果
/bookstore/book[1] 選取屬于 bookstore 子元素的第一個(gè) book 元素。
/bookstore/book[last()] 選取屬于 bookstore 子元素的最后一個(gè) book 元素。
/bookstore/book[last()-1] 選取屬于 bookstore 子元素的倒數(shù)第二個(gè) book 元素。
/bookstore/book[position()<3] 選取最前面的兩個(gè)屬于 bookstore 元素的子元素的 book 元素。
//title[@lang] 選取所有擁有名為 lang 的屬性的 title 元素。
//title[@lang='eng'] 選取所有 title 元素,且這些元素?fù)碛兄禐?eng 的 lang 屬性。
/bookstore/book[price>35.00] 選取所有 bookstore 元素的 book 元素,且其中的 price 元素的值須大于 35.00。
/bookstore/book[price>35.00]/title 選取所有 bookstore 元素中的 book 元素的 title 元素,且其中的 price 元素的值須大于 35.00。
四、通配符
通配符 描述
* 匹配任何元素節(jié)點(diǎn)
@* 匹配任何屬性節(jié)點(diǎn)
node() 匹配任何類(lèi)型的節(jié)點(diǎn)
| 選取若干路徑
例如:
路徑表達(dá)式 結(jié)果
/bookstore/* 選取 bookstore 元素的所有子節(jié)點(diǎn)
//* 選取文檔中的所有元素
//title[@*] 選取所有帶有屬性的 title 元素。
//book/title | //book/price 選取所有 book 元素的 tilte 和 price 元素。
//title | //price 選取所有文檔中的 title 和 price 元素。
/bookstore/book/title | //price 選取所有屬于 bookstore 元素的 book 元素的 title 元素,以及文檔中所有的 price 元素。
五、函數(shù)
名稱(chēng) 結(jié)果
ancestor 選取當(dāng)前節(jié)點(diǎn)的所有先輩(父、祖父等)
ancestor-or-self 選取當(dāng)前節(jié)點(diǎn)的所有先輩(父、祖父等)以及當(dāng)前節(jié)點(diǎn)本身
attribute 選取當(dāng)前節(jié)點(diǎn)的所有屬性
child 選取當(dāng)前節(jié)點(diǎn)的所有子元素。
descendant 選取當(dāng)前節(jié)點(diǎn)的所有后代元素(子、孫等)。
descendant-or-self 選取當(dāng)前節(jié)點(diǎn)的所有后代元素(子、孫等)以及當(dāng)前節(jié)點(diǎn)本身。
following 選取文檔中當(dāng)前節(jié)點(diǎn)的結(jié)束標(biāo)簽之后的所有節(jié)點(diǎn)。
namespace 選取當(dāng)前節(jié)點(diǎn)的所有命名空間節(jié)點(diǎn)
parent 選取當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn)。
preceding 選取文檔中當(dāng)前節(jié)點(diǎn)的開(kāi)始標(biāo)簽之前的所有節(jié)點(diǎn)。
preceding-sibling 選取當(dāng)前節(jié)點(diǎn)之前的所有同級(jí)節(jié)點(diǎn)。
self 選取當(dāng)前節(jié)點(diǎn)。
路徑表達(dá)式可以是絕對(duì)路徑,也可以是相對(duì)路徑。例如:
絕對(duì)位置路徑:
/step/step/...相對(duì)位置路徑:
step/step/...其中的每一步又可以是一個(gè)表達(dá)式,包括:
軸(函數(shù))(axis)
定義所選節(jié)點(diǎn)與當(dāng)前節(jié)點(diǎn)之間的樹(shù)關(guān)系
節(jié)點(diǎn)測(cè)試(node-test)
識(shí)別某個(gè)軸內(nèi)部的節(jié)點(diǎn)
零個(gè)或者更多謂語(yǔ)(predicate)
更深入地提煉所選的節(jié)點(diǎn)集
例如: 例子 結(jié)果
child::book 選取所有屬于當(dāng)前節(jié)點(diǎn)的子元素的 book 節(jié)點(diǎn)
attribute::lang 選取當(dāng)前節(jié)點(diǎn)的 lang 屬性
child::* 選取當(dāng)前節(jié)點(diǎn)的所有子元素
attribute::* 選取當(dāng)前節(jié)點(diǎn)的所有屬性
child::text() 選取當(dāng)前節(jié)點(diǎn)的所有文本子節(jié)點(diǎn)
child::node() 選取當(dāng)前節(jié)點(diǎn)的所有子節(jié)點(diǎn)
descendant::book 選取當(dāng)前節(jié)點(diǎn)的所有 book 后代
ancestor::book 選擇當(dāng)前節(jié)點(diǎn)的所有 book 先輩
ancestor-or-self::book 選取當(dāng)前節(jié)點(diǎn)的所有book先輩以及當(dāng)前節(jié)點(diǎn)(假如此節(jié)點(diǎn)是book節(jié)點(diǎn)的話(huà))
child::*/child::price 選取當(dāng)前節(jié)點(diǎn)的所有 price 孫。
六、運(yùn)算符
運(yùn)算符 描述 實(shí)例 返回值
| 計(jì)算兩個(gè)節(jié)點(diǎn)集 //book | //cd 返回所有帶有 book 和 ck 元素的節(jié)點(diǎn)集
+ 加法 6 + 4 10
- 減法 6 - 4 2
* 乘法 6 * 4 24
div 除法 8 div 4 2
= 等于 price=9.80 如果 price 是9.80,則返回 true。 如果 price 是9.90,則返回 fasle。
!= 不等于 price!=9.80 如果 price 是 9.90,則返回 true。 如果 price 是 9.98,則返回 fasle。
< 小于 price<9.80 如果price是9.00,則返回true 如果price是9.98,則返回fasle
<= 小于或等于 price<=9.80 如果 price 是9.00,則返回 true。 如果 price 是9.90,則返回 fasle。
> 大于 price>9.80 如果 price 是 9.90,則返回 true。 如果 price 是 9.80,則返回 fasle。
>= 大于或等于 price>=9.80 如果 price 是 9.90,則返回 true。 如果 price 是 9.70,則返回 fasle。
or 或 price=9.80 or price=9.70 如果 price 是 9.80,則返回 true。 如果 price 是 9.50,則返回 fasle。
and 與 price>9.00 and price<9.90 如果 price 是 9.80,則返回 true。 如果 price 是 8.50,則返回 fasle。
mod 計(jì)算除法的余數(shù) 5 mod 2 1
七、在Java中使用Xpath
在java1.5中推出了一個(gè)javax.xml.xpath包專(zhuān)門(mén)用來(lái)在java中使用Xpath表達(dá)式來(lái)讀取xml。1. 數(shù)據(jù)類(lèi)型
在學(xué)習(xí)之前首先需要注意的是:Xpath的數(shù)據(jù)并不與Java有一一對(duì)應(yīng)關(guān)系,Xpath1.0只聲明了四種數(shù)據(jù)類(lèi)型:
•node-set
•number
•boolean
•string
對(duì)應(yīng)到j(luò)ava就是:
•number 映射為 java.lang.Double
•string 映射為 java.lang.String
•boolean 映射為 java.lang.Boolean
•node-set 映射為 org.w3c.dom.NodeList
因此,在使用java的xpathAPI時(shí),需要注意返回類(lèi)型:
Java代碼
復(fù)制代碼 代碼如下:
public Object evaluate(Object item, QName returnType)throws XPathExpressionException;
public String evaluate(Object item)throws XPathExpressionException;
public Object evaluate(InputSource source, QName returnType)throws XPathExpressionException;
public String evaluate(InputSource source)throws XPathExpressionException;
復(fù)制代碼 代碼如下:
public Object evaluate(Object item, QName returnType)throws XPathExpressionException;
public String evaluate(Object item)throws XPathExpressionException;
public Object evaluate(InputSource source, QName returnType)throws XPathExpressionException;
public String evaluate(InputSource source)throws XPathExpressionException;
不指定返回類(lèi)型時(shí),缺省返回類(lèi)型為String。指定返回類(lèi)型時(shí),需要把返回值由Object類(lèi)型強(qiáng)制轉(zhuǎn)換成對(duì)應(yīng)的返回類(lèi)型。
API的使用
類(lèi)似于Dom,要得到一個(gè)Xpath對(duì)象,可以如下使用: Java代碼
復(fù)制代碼 代碼如下:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile("/bookstore//book/title/text()");
復(fù)制代碼 代碼如下:
<strong><strong> XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile("/bookstore//book/title/text()");</strong></strong>
還是以之前的xml文檔為例。要得到這個(gè)表達(dá)式的結(jié)果,我們先要得到一個(gè)輸入對(duì)象,例如一個(gè)document:
復(fù)制代碼 代碼如下:
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File("books.xml"));
NodeList list = (NodeList) expression.evaluate(document,XPathConstants.NODESET);
復(fù)制代碼 代碼如下:
<strong><strong> DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File("books.xml"));
NodeList list = (NodeList) expression.evaluate(document,XPathConstants.NODESET);</strong></strong>
這里可以看出,在使用Xpath的時(shí)候,我們好像需要很清楚的知道返回結(jié)果是什么。否則就不能得到意想的結(jié)果。
最后,我們得到一個(gè)title的list值:
復(fù)制代碼 代碼如下:
for(int i = 0;i<list.getLength();i++){ System.out.println(list.item(i).getNodeValue());
}
復(fù)制代碼 代碼如下:
<strong><strong> for(int i = 0;i</strong></strong>
復(fù)制代碼 代碼如下:
Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
復(fù)制代碼 代碼如下:
<strong><strong>Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML</strong></strong>
八、處理命令空間一般一個(gè)規(guī)范xml都會(huì)有命名空間的定義,例如:
復(fù)制代碼 代碼如下:
<strong><strong>
Hello
</strong></strong>
復(fù)制代碼 代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<tg:bookstore xmlns:tg="http://www.tibco.com/cdc/liugang"
xmlns:ns="http://www.tibco.com/cdc/liugang/ns">
<ns:book>
<tg:title>Hello</tg:title>
</ns:book>
</tg:bookstore>
xpath中定義了與節(jié)點(diǎn)名和命名空間有關(guān)的三個(gè)函數(shù):
•local-name()
•namespace-uri()
•name()
例如要查找所有在當(dāng)前文檔中定義的,元素的local名為book的結(jié)點(diǎn),則如下:
復(fù)制代碼 代碼如下:
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression compile = xpath.compile("http://*[local-name()='book']");
NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);
復(fù)制代碼 代碼如下:
<strong><strong> XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression compile = xpath.compile("http://*[local-name()='book']");
NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);</strong></strong>
如果元素定義了命名空間,則使用xpath查找時(shí)也必須指定在同一個(gè)命名空間中,即便元素使用的是缺省的命名空間,剛查找也需要定義缺省的命名空間。 例如文檔:
復(fù)制代碼 代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore xmlns="http://www.tibco.com/cdc/liugang" xmlns:tg="http://www.tibco.com/cdc/liugang/tg"
xmlns:ns="http://www.tibco.com/cdc/liugang/ns">
<ns:book>
<tg:title>Hello</tg:title>
</ns:book>
<computer>
<id>ElsIOIELdslke-1233</id>
</computer>
</bookstore>
復(fù)制代碼 代碼如下:
<strong><strong>
Hello
ElsIOIELdslke-1233
</strong></strong>
定義了三個(gè)命名空間:缺省的;xmlns:tg;xmlns:ns。 要使用命名空間,我們需要設(shè)置XPath的命名空間上下文:NamespaceContext。這是一個(gè)接口類(lèi)型,我們需要自定義去實(shí)現(xiàn)它。例如對(duì)應(yīng)于上文檔的三個(gè)命名空間,可以如下實(shí)現(xiàn):
復(fù)制代碼 代碼如下:
class CustomNamespaceContext implements NamespaceContext{
public String getNamespaceURI(String prefix) {
if(prefix.equals("ns")){
return "http://www.tibco.com/cdc/liugang/ns";
}else if(prefix.equals("tg")){
return "http://www.tibco.com/cdc/liugang/tg";
}else if(prefix.equals("df")){
return "http://www.tibco.com/cdc/liugang";
}
return XMLConstants.NULL_NS_URI;
}
public String getPrefix(String namespaceURI) {
return null;
}
public Iterator getPrefixes(String namespaceURI) {
return null;
}
}
復(fù)制代碼 代碼如下:
<strong><strong>class CustomNamespaceContext implements NamespaceContext{
public String getNamespaceURI(String prefix) {
if(prefix.equals("ns")){
return "http://www.tibco.com/cdc/liugang/ns";
}else if(prefix.equals("tg")){
return "http://www.tibco.com/cdc/liugang/tg";
}else if(prefix.equals("df")){
return "http://www.tibco.com/cdc/liugang";
}
return XMLConstants.NULL_NS_URI;
}
public String getPrefix(String namespaceURI) {
return null;
}
public Iterator getPrefixes(String namespaceURI) {
return null;
}
}</strong></strong>
方法名都非常直觀(guān)。這里只實(shí)現(xiàn)第一個(gè)方法。 這樣,如果要查找命名空間是缺省,元素名為computer的所有元素,可以如下實(shí)現(xiàn):
復(fù)制代碼 代碼如下:
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
xpath.setNamespaceContext(new CustomNamespaceContext());
XPathExpression compile = xpath.compile("http://df:computer");
NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);
for(int i = 0;i
Node item = list.item(i);
System.out.println(item.getNodeName()+" "+item.getNodeValue());
}
復(fù)制代碼 代碼如下:
<strong><strong> XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
xpath.setNamespaceContext(new CustomNamespaceContext());
XPathExpression compile = xpath.compile("http://df:computer");
NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);
for(int i = 0;i</strong></strong>
九、其他
除此之外,在java中,還可以定義擴(kuò)展的函數(shù)解釋器和變量解釋器,看XPath的方法:
復(fù)制代碼 代碼如下:
/**
*
Establish a variable resolver.
*
*
A NullPointerException is thrown if resolver is null.
*
* @param resolver Variable resolver.
*
* @throws NullPointerException If resolver is null.
*/
public void setXPathVariableResolver(XPathVariableResolver resolver);
/**
*
Establish a function resolver.
*
*
A NullPointerException is thrown if resolver is null.
*
* @param resolver XPath function resolver.
*
* @throws NullPointerException If resolver is null.
*/
public void setXPathFunctionResolver(XPathFunctionResolver resolver);
復(fù)制代碼 代碼如下:
<strong><strong> /**
* Establish a variable resolver.
*
* A <code>NullPointerException</code> is thrown if <code>resolver</code> is <code>null</code>.
*
* @param resolver Variable resolver.
*
* @throws NullPointerException If <code>resolver</code> is <code>null</code>.
*/
public void setXPathVariableResolver(XPathVariableResolver resolver);
/**
* Establish a function resolver.
*
* A <code>NullPointerException</code> is thrown if <code>resolver</code> is <code>null</code>.
*
* @param resolver XPath function resolver.
*
* @throws NullPointerException If <code>resolver</code> is <code>null</code>.
*/
public void setXPathFunctionResolver(XPathFunctionResolver resolver);</strong></strong>
相關(guān)文章
SpringBoot導(dǎo)出Excel的四種實(shí)現(xiàn)方式
近期接到了一個(gè)小需求,要將系統(tǒng)中的數(shù)據(jù)導(dǎo)出為Excel,且能將Excel數(shù)據(jù)導(dǎo)入到系統(tǒng),對(duì)于大多數(shù)研發(fā)人員來(lái)說(shuō),這算是一個(gè)最基本的操作了,本文就給大家總結(jié)一下SpringBoot導(dǎo)出Excel的四種實(shí)現(xiàn)方式,需要的朋友可以參考下2024-01-01基于Java方式實(shí)現(xiàn)數(shù)據(jù)同步
這篇文章主要為大家詳細(xì)介紹了基于Java方式實(shí)現(xiàn)數(shù)據(jù)同步,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08IDEA項(xiàng)目代碼上傳gitlab遠(yuǎn)程倉(cāng)庫(kù)過(guò)程圖解
這篇文章主要介紹了IDEA項(xiàng)目代碼上傳gitlab遠(yuǎn)程倉(cāng)庫(kù)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Java輕松入門(mén)冒泡?選擇?插入?希爾?歸并排序算法
這篇文章主要介紹了Java常用的排序算法及代碼實(shí)現(xiàn),在Java開(kāi)發(fā)中,對(duì)排序的應(yīng)用需要熟練的掌握,這樣才能夠確保Java學(xué)習(xí)時(shí)候能夠有扎實(shí)的基礎(chǔ)能力。那Java有哪些排序算法呢?本文小編就來(lái)詳細(xì)說(shuō)說(shuō)Java常見(jiàn)的排序算法,需要的朋友可以參考一下2022-02-02Java中equals()知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家分享的是關(guān)于Java中equals()知識(shí)點(diǎn)總結(jié)內(nèi)容,需要的朋友們可以學(xué)習(xí)參考下。2020-03-03SpringCloud整合Consul的實(shí)現(xiàn)
這篇文章主要介紹了SpringCloud整合Consul的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01java并發(fā)編程專(zhuān)題(二)----如何創(chuàng)建并運(yùn)行java線(xiàn)程
這篇文章主要介紹了java并發(fā)編程如何創(chuàng)建并運(yùn)行java線(xiàn)程,文中講解非常詳細(xì),示例代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06