XPath可以快速定位到Xml中的節點或者屬性。XPath語法很簡單,但是強大夠用,它也是使用xslt的基礎知識。


示例Xml:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<? xml version = "1.0" encoding = "utf-8" ?>
< pets >
   < cat color = "black" weight = "10" >
     < price >100</ price >
     < desc >this is a black cat</ desc >
   </ cat >
   < cat color = "white" weight = "9" >
     < price >80</ price >
     < desc >this is a white cat</ desc >
   </ cat >
   < cat color = "yellow" weight = "15" >
     < price >80</ price >
     < desc >this is a yellow cat</ desc >
   </ cat >
 
 
   < dog color = "black" weight = "10" >
     < price >100</ price >
     < desc >this is a black dog</ desc >
   </ dog >
   < dog color = "white" weight = "9" >
     < price >80</ price >
     < desc >this is a white dog</ desc >
   </ dog >
   < dog color = "yellow" weight = "15" >
     < price >80</ price >
     < desc >this is a yellow dog</ desc >
   </ dog >
</ pets >

XPath的語法:

1. XPath中的符號

符號

說明

示例

示例說明

/

表示從根節點開始選擇

/pets

選擇根節點pets

表示節點和子節點之間的間隔符

/pets/dog

選擇pets節點下的dog節點

//xx

表示從整個xml文檔中查找,而不考慮當前節點位置

//price

選擇文檔中所有的price節點

.

單個英文半角句點表示選擇當前節點

/pets/.

選擇pets節點

..

雙點,表示選擇父節點

/pets/dog[0]/..

表示pets節點,也就是第一個dog節點的父節點

@xx

表示選擇屬性

//dog/@color

表示選擇所有dog節點的color屬性集合

[…]

中括號表示選擇條件,括號內為條件

//dog[@color=’white’]

所有color為white的dog節點

//dog[/price<100]

所有price字節點值小於100的dog節點

中括號內數字為節點索引,類似c#等語言中的數組,數組下標是從1開始的

//dog[1]

第1個dog節點

//dog[last()]

最后一個dog節點,last()是xPath內置函數

|

單豎杠表示合並節點結合

//dog[@color=’white’] | //cat[@color=’white’]

color屬性為white的dog節點和color屬性為white的cat節點

*

星號表示任何名字的節點或者屬性

//dog/*

表示dog節點的所有子節點

//dog/@*

表示dog節點的所有屬性節點

2. XPath數學運算符
+ 加號表示加
- 表示數字相減
* 表示乘以
div 表示除以,這里數學上的除號/已經被用作節點之間分隔符了
mod 表示取余
3. XPath邏輯運算符
= 等於,相當於c#中的 ==
!= 不等於
> 大於
>= 大於等於
< 小於
<= 小於等於
and 並且 與關系
or 或者 或關系
4. XPath Axes 從字面翻譯這個是XPath軸的意思,但根據我的理解這個翻譯成XPath節點關系運算關鍵字更合適,就是一組關鍵字加上::雙冒號表示和當前節點有關系的一個或者一組節點.
使用語法: axisname::nodetest[predicate] 即軸名字::節點名字[取節點條件]
具體說明如下:

關鍵字

說明

示例

示例說明

ancestor

當前節點的父祖節點

ancestor::pig

當前節點的祖先節點中的pig節點

ancestor-or-self

當前節點以及其父祖節點

ancestor::pig

 

attribute

當前節點的所有屬性

attribute::weight

相當於@weight,attribute::和@是等價的

child

當前節點的所有字節點

child::*[name()!=’price’]

選擇名字不是price的子節點

descendant

子孫節點

descendant::*[@*]

有屬性的子孫節點

descendant-or-self

子孫節點以及當前節點

descendant-or-self::*

 

following

Xml文檔中當前節點之后的所有節點

following::*

 

following-sibling

當前節點的同父弟弟節點

following-sibling::

 

preceding

Xml文檔中當前節點之前的所有節點

preceding::*

 

namespace

選取當前節點的所有命名空間節點

namespace::*

 

parent

當前節點的父節點

parent::

相當於雙點..

preceding-sibling

當前節點之后的同父兄節點

preceding-sibling::*

 

self

當前節點

self::*

相當於單點.

 
5. 常用的XPath函數介紹:
在XPath表達式中常用的函數有下面兩個:
position() 表示節點的序號例如 //cat[position() = 2] 表示取序號為2的dog節點
last() 表示取最后一個節點 //cat[last()] 
name() 表示當前節點名字 /pets/*[name() != 'pig'] 表示/pets下名字不是pig的子節點
XPath的函數還有很多,包括字符串函數,數字函數和時間函數等,具體可以參考w3的網站。
以上是XPath的語法,下面我們看下如何在.Net中使用XPath
在.Net中可以通過XPathDocument或者XmlDocument類使用XPath。XPathDocument是只讀的方式定位Xml節點或者屬性文本等,而XmlDocument則是可讀寫的。
如下代碼示例展示了如何使用XPathDocument和XmlDocument
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.XPath;
using System.Xml;
 
namespace UseXPathDotNet
{
     class Program
     {
         static void Main( string [] args)
         {
             UseXPathWithXPathDocument();
 
             UseXPathWithXmlDocument();
 
             Console.Read();
         }
 
         static void UseXPathWithXmlDocument()
         {
             XmlDocument doc = new XmlDocument();
             doc.Load( "http://www.cnblogs.com/yukaizhao/rss" );
             //使用xPath選擇需要的節點
             XmlNodeList nodes = doc.SelectNodes( "/rss/channel/item[position()<=10]" );
             foreach (XmlNode item in nodes)
             {
                 string title = item.SelectSingleNode( "title" ).InnerText;
                 string url = item.SelectSingleNode( "link" ).InnerText;
                 Console.WriteLine( "{0} = {1}" , title, url);
             }
         }
 
         static void UseXPathWithXPathDocument()
         {
             XPathDocument doc = new XPathDocument( "http://www.cnblogs.com/yukaizhao/rss" );
             XPathNavigator xPathNav = doc.CreateNavigator();
             //使用xPath取rss中最新的10條隨筆
             XPathNodeIterator nodeIterator = xPathNav.Select( "/rss/channel/item[position()<=10]" );
             while (nodeIterator.MoveNext())
             {
                 XPathNavigator itemNav = nodeIterator.Current;
                 string title = itemNav.SelectSingleNode( "title" ).Value;
                 string url = itemNav.SelectSingleNode( "link" ).Value;
                 Console.WriteLine( "{0} = {1}" ,title,url);
             }
 
         }
     }
}

XPath使用示例,請看下面的代碼注釋 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
 
namespace UseXPath1
{
     class Program
     {
         static void Main( string [] args)
         {
             string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<pets>
   <cat color=""black"" weight=""10"" count=""4"">
     <price>100</price>
     <desc>this is a black cat</desc>
   </cat>
   <cat color=""white"" weight=""9"" count=""5"">
     <price>80</price>
     <desc>this is a white cat</desc>
   </cat>
   <cat color=""yellow"" weight=""15"" count=""1"">
     <price>110</price>
     <desc>this is a yellow cat</desc>
   </cat>
 
 
   <dog color=""black"" weight=""10"" count=""7"">
     <price>114</price>
     <desc>this is a black dog</desc>
   </dog>
   <dog color=""white"" weight=""9"" count=""4"">
     <price>80</price>
     <desc>this is a white dog</desc>
   </dog>
   <dog color=""yellow"" weight=""15"" count=""15"">
     <price>80</price>
     <desc>this is a yellow dog</desc>
   </dog>
 
     <pig color=""white"" weight=""100"" count=""2"">
     <price>8000</price>
     <desc>this is a white pig</desc>   
     </pig>
</pets>" ;
 
             using (StringReader rdr = new StringReader(xml))
             {
                 XmlDocument doc = new XmlDocument();
                 doc.Load(rdr);
 
                 //取所有pets節點下的dog字節點
                 XmlNodeList nodeListAllDog = doc.SelectNodes( "/pets/dog" );
 
                 //所有的price節點
                 XmlNodeList allPriceNodes = doc.SelectNodes( "//price" );
 
                 //取最后一個price節點
                 XmlNode lastPriceNode = doc.SelectSingleNode( "//price[last()]" );
 
                 //用雙點號取price節點的父節點
                 XmlNode lastPriceParentNode = lastPriceNode.SelectSingleNode( ".." );
 
                 //選擇weight*count=40的所有動物,使用通配符*
                 XmlNodeList nodeList = doc.SelectNodes( "/pets/*[@weight*@count=40]" );
 
                 //選擇除了pig之外的所有動物,使用name()函數返回節點名字
                 XmlNodeList animalsExceptPigNodes = doc.SelectNodes( "/pets/*[name() != 'pig']" );
                
 
                 //選擇價格大於100而不是pig的動物
                 XmlNodeList priceGreaterThan100s = doc.SelectNodes( "/pets/*[price div @weight >10 and name() != 'pig']" );
                 foreach (XmlNode item in priceGreaterThan100s)
                 {
                     Console.WriteLine(item.OuterXml);
                 }
 
                 //選擇第二個dog節點
                 XmlNode theSecondDogNode = doc.SelectSingleNode( "//dog[position() = 2]" );
 
                 //使用xpath ,axes 的 parent 取父節點
                 XmlNode parentNode = theSecondDogNode.SelectSingleNode( "parent::*" );
 
                 //使用xPath選擇第二個dog節點前面的所有dog節點
                 XmlNodeList dogPresibling = theSecondDogNode.SelectNodes( "preceding::dog" );
 
                 //取文檔的所有子孫節點price
                 XmlNodeList childrenNodes = doc.SelectNodes( "descendant::price" );
             }
 
             Console.Read();
         }
     }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM