欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2013年06月04日 11:44:43   作者:  
本篇文章是對XPath進行了詳細的分析介紹,需要的朋友參考下
復制代碼 代碼如下:

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());
  }
 }
}

一、結點類型
XPath中有七種結點類型:元素、屬性、文本、命名空間、處理指令、注釋以及文檔節(jié)點(或成為根節(jié)點)。 文檔的根節(jié)點即是文檔結點;對應屬性有屬性結點,元素有元素結點。
二、常用路徑表達式
表達式 描述
nodename      選取此節(jié)點的所有子節(jié)點
/             從根節(jié)點選取
//  從匹配選擇的當前節(jié)點選擇文檔中的節(jié)點,而不考慮它們的位置
.   選取當前節(jié)點
..    選取當前節(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> 

則:
路徑表達式 結果
bookstore 選取 bookstore 元素的所有子節(jié)點
/bookstore 選取根元素 bookstore 注釋:假如路徑起始于正斜杠( / ),則此路徑始終代表到某元素的絕對路徑!
bookstore/book 選取所有屬于 bookstore 的子元素的 book 元素。
//book 選取所有 book 子元素,而不管它們在文檔中的位置。
bookstore//book 選擇所有屬于 bookstore 元素的后代的 book 元素,而不管它們位于 bookstore 之下的什么位置。
//@lang 選取所有名為 lang 的屬性。
三、限定語
用來查找某個特定的節(jié)點或者包含某個指定的值的節(jié)點。以方括號括起。
例如:
路徑表達式 結果
/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。
四、通配符
通配符 描述
* 匹配任何元素節(jié)點
@* 匹配任何屬性節(jié)點
node() 匹配任何類型的節(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 元素。

五、函數
名稱 結果
ancestor 選取當前節(jié)點的所有先輩(父、祖父等)
ancestor-or-self 選取當前節(jié)點的所有先輩(父、祖父等)以及當前節(jié)點本身
attribute 選取當前節(jié)點的所有屬性
child 選取當前節(jié)點的所有子元素。
descendant 選取當前節(jié)點的所有后代元素(子、孫等)。
descendant-or-self 選取當前節(jié)點的所有后代元素(子、孫等)以及當前節(jié)點本身。
following 選取文檔中當前節(jié)點的結束標簽之后的所有節(jié)點。
namespace 選取當前節(jié)點的所有命名空間節(jié)點
parent 選取當前節(jié)點的父節(jié)點。
preceding 選取文檔中當前節(jié)點的開始標簽之前的所有節(jié)點。
preceding-sibling 選取當前節(jié)點之前的所有同級節(jié)點。
self 選取當前節(jié)點。
路徑表達式可以是絕對路徑,也可以是相對路徑。例如:
絕對位置路徑:
/step/step/...相對位置路徑:
step/step/...其中的每一步又可以是一個表達式,包括:
軸(函數)(axis)
定義所選節(jié)點與當前節(jié)點之間的樹關系
節(jié)點測試(node-test)
識別某個軸內部的節(jié)點
零個或者更多謂語(predicate)
更深入地提煉所選的節(jié)點集
例如: 例子 結果
child::book 選取所有屬于當前節(jié)點的子元素的 book 節(jié)點
attribute::lang 選取當前節(jié)點的 lang 屬性
child::* 選取當前節(jié)點的所有子元素
attribute::* 選取當前節(jié)點的所有屬性
child::text() 選取當前節(jié)點的所有文本子節(jié)點
child::node() 選取當前節(jié)點的所有子節(jié)點
descendant::book 選取當前節(jié)點的所有 book 后代
ancestor::book 選擇當前節(jié)點的所有 book 先輩
ancestor-or-self::book 選取當前節(jié)點的所有book先輩以及當前節(jié)點(假如此節(jié)點是book節(jié)點的話)
child::*/child::price 選取當前節(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 計算除法的余數 5 mod 2 1

七、在Java中使用Xpath
在java1.5中推出了一個javax.xml.xpath包專門用來在java中使用Xpath表達式來讀取xml。1. 數據類型
在學習之前首先需要注意的是:Xpath的數據并不與Java有一一對應關系,Xpath1.0只聲明了四種數據類型:
•node-set
•number
•boolean
•string

對應到java就是:
•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類型強制轉換成對應的返回類型。 
 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文檔為例。要得到這個表達式的結果,我們先要得到一個輸入對象,例如一個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的時候,我們好像需要很清楚的知道返回結果是什么。否則就不能得到意想的結果。
最后,我們得到一個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é)點名和命名空間有關的三個函數:
•local-name()
•namespace-uri()
•name()
例如要查找所有在當前文檔中定義的,元素的local名為book的結點,則如下:
復制代碼 代碼如下:

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。 要使用命名空間,我們需要設置XPath的命名空間上下文:NamespaceContext。這是一個接口類型,我們需要自定義去實現它。例如對應于上文檔的三個命名空間,可以如下實現:
復制代碼 代碼如下:

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> 

方法名都非常直觀。這里只實現第一個方法。 這樣,如果要查找命名空間是缺省,元素名為computer的所有元素,可以如下實現:
復制代碼 代碼如下:

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中,還可以定義擴展的函數解釋器和變量解釋器,看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> 

相關文章

  • SpringBoot導出Excel的四種實現方式

    SpringBoot導出Excel的四種實現方式

    近期接到了一個小需求,要將系統中的數據導出為Excel,且能將Excel數據導入到系統,對于大多數研發(fā)人員來說,這算是一個最基本的操作了,本文就給大家總結一下SpringBoot導出Excel的四種實現方式,需要的朋友可以參考下
    2024-01-01
  • 基于Java方式實現數據同步

    基于Java方式實現數據同步

    這篇文章主要為大家詳細介紹了基于Java方式實現數據同步,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • IDEA項目代碼上傳gitlab遠程倉庫過程圖解

    IDEA項目代碼上傳gitlab遠程倉庫過程圖解

    這篇文章主要介紹了IDEA項目代碼上傳gitlab遠程倉庫過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-09-09
  • Java輕松入門冒泡?選擇?插入?希爾?歸并排序算法

    Java輕松入門冒泡?選擇?插入?希爾?歸并排序算法

    這篇文章主要介紹了Java常用的排序算法及代碼實現,在Java開發(fā)中,對排序的應用需要熟練的掌握,這樣才能夠確保Java學習時候能夠有扎實的基礎能力。那Java有哪些排序算法呢?本文小編就來詳細說說Java常見的排序算法,需要的朋友可以參考一下
    2022-02-02
  • Java中equals()知識點總結

    Java中equals()知識點總結

    在本篇文章里小編給大家分享的是關于Java中equals()知識點總結內容,需要的朋友們可以學習參考下。
    2020-03-03
  • SpringCloud整合Consul的實現

    SpringCloud整合Consul的實現

    這篇文章主要介紹了SpringCloud整合Consul的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • java并發(fā)編程專題(二)----如何創(chuàng)建并運行java線程

    java并發(fā)編程專題(二)----如何創(chuàng)建并運行java線程

    這篇文章主要介紹了java并發(fā)編程如何創(chuàng)建并運行java線程,文中講解非常詳細,示例代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-06-06
  • 五分鐘手擼一個Spring容器(萌芽版)

    五分鐘手擼一個Spring容器(萌芽版)

    Spring的兩大內核分別是IOC和AOP,其中最最核心的是IOC。這篇文章主要介紹了五分鐘,手擼一個Spring容器的相關知識,需要的朋友可以參考下
    2022-03-03
  • Java發(fā)送post方法詳解

    Java發(fā)送post方法詳解

    這篇文章主要介紹了Java發(fā)送post方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-04-04
  • Java中Steam流的用法詳解

    Java中Steam流的用法詳解

    Stream是Java?8?API添加的一個新的抽象,稱為流Stream,本文主要介紹了Java中Steam流的用法詳解,具有一定的參考價值,感興趣的可以了解一下
    2023-04-04

最新評論