XPath引见
XPath介绍
什么是 XPath
XPath 即为 XML 路径语言,它是一种用来确定 XML(标准通用标记语言的子集)文档中某部分位置的语言。XPath 基于 XML 的树状结构,提供在数据结构树中找寻节点的能力。详细语法教程,请参考W3School 的 XPath 。
XPath 原理
XPath 将XML数据转换为DOM 树状结构,并提供在数据结构树中寻找节点的能力。
XPath 语法
XPath 使用路径表达式在 XML 文档(字符串)中选取节点,节点是通过沿着路径来选取的。路径由节点名组成,节点之间以"/"分割。下面以例子说明:
测试XML 数据
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>ErikT.Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
1. 选取所有book的price节点值
2. xpath: /bookstore/book/price/text()
3. 返回: [30.00,29.99,39.95]
4. 条件表达式选取 author 为 J K. Rowling 的 book 的 title 值
5. xpath: /bookstore/book[author="JK.Rowling"]/title/text()
6. 返回: Harry Potter
7. 属性值的处理选取 category 为 “WEB” 的书的 title 的 lang 属性值
8. xpath: /bookstore/book[@category="WEB"]/title/@lang
9. 返回: en