1. 程式人生 > >XPath語法 在C#中使用XPath示例

XPath語法 在C#中使用XPath示例

基礎知識 border 簡單 nbsp 定位 spa table adding white

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

表示選擇屬性

[email protected]

表示選擇所有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節點的所有屬性節點

XPath語法 在C#中使用XPath示例