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é)點類型
XPath中有七種結(jié)點類型:元素、屬性、文本、命名空間、處理指令、注釋以及文檔節(jié)點(或成為根節(jié)點)。 文檔的根節(jié)點即是文檔結(jié)點;對應(yīng)屬性有屬性結(jié)點,元素有元素結(jié)點。
二、常用路徑表達式
表達式 描述
nodename 選取此節(jié)點的所有子節(jié)點
/ 從根節(jié)點選取
// 從匹配選擇的當(dāng)前節(jié)點選擇文檔中的節(jié)點,而不考慮它們的位置
. 選取當(dāng)前節(jié)點
.. 選取當(dāng)前節(jié)點的父節(jié)點
@ 選取屬性
例如有文檔:
<?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>
則:
路徑表達式 結(jié)果
bookstore 選取 bookstore 元素的所有子節(jié)點
/bookstore 選取根元素 bookstore 注釋:假如路徑起始于正斜杠( / ),則此路徑始終代表到某元素的絕對路徑!
bookstore/book 選取所有屬于 bookstore 的子元素的 book 元素。
//book 選取所有 book 子元素,而不管它們在文檔中的位置。
bookstore//book 選擇所有屬于 bookstore 元素的后代的 book 元素,而不管它們位于 bookstore 之下的什么位置。
//@lang 選取所有名為 lang 的屬性。
三、限定語
用來查找某個特定的節(jié)點或者包含某個指定的值的節(jié)點。以方括號括起。
例如:
路徑表達式 結(jié)果
/bookstore/book[1] 選取屬于 bookstore 子元素的第一個 book 元素。
/bookstore/book[last()] 選取屬于 bookstore 子元素的最后一個 book 元素。
/bookstore/book[last()-1] 選取屬于 bookstore 子元素的倒數(shù)第二個 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。
四、通配符
通配符 描述
* 匹配任何元素節(jié)點
@* 匹配任何屬性節(jié)點
node() 匹配任何類型的節(jié)點
| 選取若干路徑
例如:
路徑表達式 結(jié)果
/bookstore/* 選取 bookstore 元素的所有子節(jié)點
//* 選取文檔中的所有元素
//title[@*] 選取所有帶有屬性的 title 元素。
//book/title | //book/price 選取所有 book 元素的 tilte 和 price 元素。
//title | //price 選取所有文檔中的 title 和 price 元素。
/bookstore/book/title | //price 選取所有屬于 bookstore 元素的 book 元素的 title 元素,以及文檔中所有的 price 元素。
五、函數(shù)
名稱 結(jié)果
ancestor 選取當(dāng)前節(jié)點的所有先輩(父、祖父等)
ancestor-or-self 選取當(dāng)前節(jié)點的所有先輩(父、祖父等)以及當(dāng)前節(jié)點本身
attribute 選取當(dāng)前節(jié)點的所有屬性
child 選取當(dāng)前節(jié)點的所有子元素。
descendant 選取當(dāng)前節(jié)點的所有后代元素(子、孫等)。
descendant-or-self 選取當(dāng)前節(jié)點的所有后代元素(子、孫等)以及當(dāng)前節(jié)點本身。
following 選取文檔中當(dāng)前節(jié)點的結(jié)束標簽之后的所有節(jié)點。
namespace 選取當(dāng)前節(jié)點的所有命名空間節(jié)點
parent 選取當(dāng)前節(jié)點的父節(jié)點。
preceding 選取文檔中當(dāng)前節(jié)點的開始標簽之前的所有節(jié)點。
preceding-sibling 選取當(dāng)前節(jié)點之前的所有同級節(jié)點。
self 選取當(dāng)前節(jié)點。
路徑表達式可以是絕對路徑,也可以是相對路徑。例如:
絕對位置路徑:
/step/step/...相對位置路徑:
step/step/...其中的每一步又可以是一個表達式,包括:
軸(函數(shù))(axis)
定義所選節(jié)點與當(dāng)前節(jié)點之間的樹關(guān)系
節(jié)點測試(node-test)
識別某個軸內(nèi)部的節(jié)點
零個或者更多謂語(predicate)
更深入地提煉所選的節(jié)點集
例如: 例子 結(jié)果
child::book 選取所有屬于當(dāng)前節(jié)點的子元素的 book 節(jié)點
attribute::lang 選取當(dāng)前節(jié)點的 lang 屬性
child::* 選取當(dāng)前節(jié)點的所有子元素
attribute::* 選取當(dāng)前節(jié)點的所有屬性
child::text() 選取當(dāng)前節(jié)點的所有文本子節(jié)點
child::node() 選取當(dāng)前節(jié)點的所有子節(jié)點
descendant::book 選取當(dāng)前節(jié)點的所有 book 后代
ancestor::book 選擇當(dāng)前節(jié)點的所有 book 先輩
ancestor-or-self::book 選取當(dāng)前節(jié)點的所有book先輩以及當(dāng)前節(jié)點(假如此節(jié)點是book節(jié)點的話)
child::*/child::price 選取當(dāng)前節(jié)點的所有 price 孫。
六、運算符
運算符 描述 實例 返回值
| 計算兩個節(jié)點集 //book | //cd 返回所有帶有 book 和 ck 元素的節(jié)點集
+ 加法 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 計算除法的余數(shù) 5 mod 2 1
七、在Java中使用Xpath
在java1.5中推出了一個javax.xml.xpath包專門用來在java中使用Xpath表達式來讀取xml。1. 數(shù)據(jù)類型
在學(xué)習(xí)之前首先需要注意的是:Xpath的數(shù)據(jù)并不與Java有一一對應(yīng)關(guān)系,Xpath1.0只聲明了四種數(shù)據(jù)類型:
•node-set
•number
•boolean
•string
對應(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時,需要注意返回類型:
Java代碼
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;
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;
不指定返回類型時,缺省返回類型為String。指定返回類型時,需要把返回值由Object類型強制轉(zhuǎn)換成對應(yīng)的返回類型。
API的使用
類似于Dom,要得到一個Xpath對象,可以如下使用: Java代碼
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile("/bookstore//book/title/text()");
<strong><strong> XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile("/bookstore//book/title/text()");</strong></strong>
還是以之前的xml文檔為例。要得到這個表達式的結(jié)果,我們先要得到一個輸入對象,例如一個document:
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> 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的時候,我們好像需要很清楚的知道返回結(jié)果是什么。否則就不能得到意想的結(jié)果。
最后,我們得到一個title的list值:
for(int i = 0;i<list.getLength();i++){ System.out.println(list.item(i).getNodeValue());
}
<strong><strong> for(int i = 0;i</strong></strong>
Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
<strong><strong>Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML</strong></strong>
八、處理命令空間一般一個規(guī)范xml都會有命名空間的定義,例如:
<strong><strong>
Hello
</strong></strong>
<?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é)點名和命名空間有關(guān)的三個函數(shù):
•local-name()
•namespace-uri()
•name()
例如要查找所有在當(dāng)前文檔中定義的,元素的local名為book的結(jié)點,則如下:
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> 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查找時也必須指定在同一個命名空間中,即便元素使用的是缺省的命名空間,剛查找也需要定義缺省的命名空間。 例如文檔:
<?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>
<strong><strong>
Hello
ElsIOIELdslke-1233
</strong></strong>
定義了三個命名空間:缺省的;xmlns:tg;xmlns:ns。 要使用命名空間,我們需要設(shè)置XPath的命名空間上下文:NamespaceContext。這是一個接口類型,我們需要自定義去實現(xiàn)它。例如對應(yīng)于上文檔的三個命名空間,可以如下實現(xiàn):
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>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>
方法名都非常直觀。這里只實現(xiàn)第一個方法。 這樣,如果要查找命名空間是缺省,元素名為computer的所有元素,可以如下實現(xiàn):
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());
}
<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中,還可以定義擴展的函數(shù)解釋器和變量解釋器,看XPath的方法:
/**
*
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);
<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>