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
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
"/" 从根节点开始选择,节点之间的分隔符
<!-- 选择根节点 pets -->
/pets
<!-- 选择根节点 pets 下的所有 dog 节点 -->
/pets/dog

"//" 从整个xml文档中查找,而不考虑当前节点位置
<!-- 选择文档中所有的 price 节点 -->
//price

"." 单个英文半角句点表示选择当前节点
<!-- 选择pets节点 -->
/pets/.

".." 双点,表示选择父节点
<!-- 选择 pets 节点下的第一个 dog 节点的父节点,也就是选择 pets 节点, -->
/pets/dog[0]/..

"@xx" 选择属性
<!-- 选择所有dog节点的color属性集合 -->
//dog/@color

"[…]" 表示选择条件,括号内为条件
<!-- 所有 color 为 white 的 dog 节点 -->
//dog[@color=’white’]
<!-- 所有 price 字节点值小于100的 dog 节点 -->
//dog[/price<100]

<!-- 第1个 dog 节点 -->
//dog[1]
<!-- 最后一个 dog 节点 -->
//dog[last()]

"|" 单竖杠表示合并节点结合
<!-- color 属性为 white 的 dog 节点和 color 属性为 white 的 cat 节点 -->
//dog[@color=’white’] | //cat[@color=’white’]

"*" 表示任何名字的节点或者属性
//dog/*
//dog/@*

数学运算符

+ - * div mod

常用 Axes

1
2
3
4
5
6
7
8
9
10
11
12
<!--当前节点的所有字节点-->
child::*[name()!=’price’]
<!--有属性的子孙节点-->
descendant::*[@*]
<!--当前节点之后的所有节点-->
following::*
<!--当前节点之后的同父兄弟节点-->
following-sibling::
<!--同 following ,当前节点之前-->
preceding::* || preceding-sibling::*

string xPath = "//cat[@color='color' and @weight='15']/following-sibling::dog[contains(@color,'w') and @weight!='9']";

常用函数

  • position()
  • last()
  • name()

扩展

1
2
3
4
5
6
7
8
9
10
11
12
XmlDocument doc = new XmlDocument();
doc.Load(@".\BookList.xml");

XPathNavigator nav =doc.CreateNavigator();
nav.MoveToRoot();

XslTransform xt = new XslTransform();
xt.Load(@".\BookList.xslt");

XmlTextWriter writer = new XmlTextWriter(Console.Out);

xt.Transform(nav, null, writer);

Xpath 用法