麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > Java > 正文

深入XPath的詳解以及Java示例代碼分析

2019-11-26 16:04:28
字體:
供稿:網(wǎng)友
復(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é)點類型
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é)點
@     選取屬性
例如有文檔:
復(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> 

則:
路徑表達式 結(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代碼
復(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; 

不指定返回類型時,缺省返回類型為String。指定返回類型時,需要把返回值由Object類型強制轉(zhuǎn)換成對應(yīng)的返回類型。 
 API的使用
類似于Dom,要得到一個Xpath對象,可以如下使用: 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文檔為例。要得到這個表達式的結(jié)果,我們先要得到一個輸入對象,例如一個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的時候,我們好像需要很清楚的知道返回結(jié)果是什么。否則就不能得到意想的結(jié)果。
最后,我們得到一個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> 

八、處理命令空間一般一個規(guī)范xml都會有命名空間的定義,例如:
復(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é)點名和命名空間有關(guān)的三個函數(shù):
•local-name()
•namespace-uri()
•name()
例如要查找所有在當(dāng)前文檔中定義的,元素的local名為book的結(jié)點,則如下:
復(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查找時也必須指定在同一個命名空間中,即便元素使用的是缺省的命名空間,剛查找也需要定義缺省的命名空間。 例如文檔:
復(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> 

定義了三個命名空間:缺省的;xmlns:tg;xmlns:ns。 要使用命名空間,我們需要設(shè)置XPath的命名空間上下文:NamespaceContext。這是一個接口類型,我們需要自定義去實現(xiàn)它。例如對應(yīng)于上文檔的三個命名空間,可以如下實現(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> 

方法名都非常直觀。這里只實現(xiàn)第一個方法。 這樣,如果要查找命名空間是缺省,元素名為computer的所有元素,可以如下實現(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中,還可以定義擴展的函數(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> 

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 91精品国产91久久久久久 | 国产1区2区3区中文字幕 | 黄色成年在线观看 | 免费观看黄色一级视频 | 亚洲一区二区三区精品在线观看 | 一区二区三区黄色 | 97视频一二区 | 欧美精品免费一区二区三区 | 久久国产精品二国产精品 | free台湾极品性hd | jizzyouxxxx| 国产精品色在线网站 | 欧美女同hd | 中文字幕在线亚洲 | 日本免费一区二区三区四区 | 亚州视频在线 | 嗯~啊~弄嗯~啊h高潮视频 | 精品国产一区二区三区四区在线 | 欧美一级免费高清 | 毛片在线免费播放 | 成人免费看视频 | av在线在线 | 91成人在线免费观看 | 九九热在线视频观看这里只有精品 | 九草视频 | 国产精品av久久久久久网址 | 成人一级片毛片 | 黄色av网站在线观看 | 欧美一区黄色 | 亚洲va久久久噜噜噜久牛牛影视 | 人人舔人人射 | 久久成年网 | 久久久久国产成人免费精品免费 | 激情宗合网 | 久久草在线观看视频 | 性少妇chinesevideo | 日韩精品久久久久久久电影99爱 | 性毛片视频| 久久精品99国产国产精 | 久久精品欧美一区二区三区不卡 | 毛片在线免费观看网址 |