0
点赞
收藏
分享

微信扫一扫

【XPATH 语法】

崭新的韭菜 2022-03-18 阅读 26

XPATH 数据解析


解析样例:
地址: 样例数据来源

<bookstore>
	<book category="children">
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year>
		<price>29.99</price>
	</book>
	<book category="cooking">
		<title lang="en">Everyday Italian</title>
		<author>Giada De Laurentiis</author>
		<year>2005</year>
		<price>30.00</price>
	</book>
	<book category="web" cover="paperback">
		<title lang="en">Learning XML</title>
		<author>Erik T. Ray</author>
		<year>2003</year>
		<price>39.95</price>
	</book>
	<book category="web">
		<title lang="en">XQuery Kick Start</title>
		<author>James McGovern</author>
		<author>Per Bothner</author>
		<author>Kurt Cagle</author>
		<author>James Linn</author>
		<author>Vaidyanathan Nagarajan</author>
		<year>2003</year>
		<price>49.99</price>
	</book>
</bookstore>

基础语法

/ 代表根路径 表示绝对路径 从第一个元素开始算起
// 代表相对路径 表示 满足条件的所有情况

. 选取 当前 节点
.. 选取 当前 节点的 父 节点

* 任何所有 类型

数据选择:
/text() 获取 元素标签的文本
//text() 获取 元素标签下的 所有文本
/@href 提取 标签元素的 href 属性的 值

例子:

<book category="web">
	<title lang="en">XQuery Kick Start</title>
	<author>James McGovern</author>
	<author>Per Bothner</author>
	<author>Kurt Cagle</author>
	<author>James Linn</author>
	<author>Vaidyanathan Nagarajan</author>
	<year>2003</year>
	<price>49.99</price>
</book>

一、
语法: /title
含义: 获取 根路径 下面的 title 标签
结果: 由于 根路径下面 第一层不存在 title 标签,因此 没有结果

二、
语法: /book
含义: 获取 根路径 下的 book 标签
结果:

<book category="web">
	<title lang="en">XQuery Kick Start</title>
	<author>James McGovern</author>
	<author>Per Bothner</author>
	<author>Kurt Cagle</author>
	<author>James Linn</author>
	<author>Vaidyanathan Nagarajan</author>
	<year>2003</year>
	<price>49.99</price>
</book>

三、
语法: //title
含义: 获取 相对路径 下的 所有 title 标签
结果:

<title lang="en">XQuery Kick Start</title>

XPATH 属性选择器

//*[@class='school'] 选择所有 属性有 class=‘school’ 的标签元素
例子:

<book category="web" cover="paperback">
	<title lang="en">Learning XML</title>
	<author>Erik T. Ray</author>
	<year>2003</year>
	<price>39.95</price>
</book>

方法:
语法: //*[@lang='en']
含义: 选择 包含 lang 属性 并且 lang 属性 绝对等于 en 的所有元素
结果:

<title lang="en">Learning XML</title>

拓展:

选择 不包含 class 属性的 span 元素: //span[not(@class)]
选择 不包含 class 和 id 属性的 span 元素: //span[not(@class) and not(@id)]
选择 不包含 class=‘school’ 的 span 元素: //span[not(contains(@class,'school'))]
选择 包含 class=‘school’ 的 span 元素: //span[contains(@class,'school')]

选择 找到的 所有 元素的 第一个 元素: //body/p[1]

第一个 元素 使用 : [1]
最后一个元素 使用: [last()]
选择 倒数第二个元素 使用 : [last()-1]
选择 前 两个 元素 使用: [position()<3]
选择 所有 有 class 属性的 元素 : [@class]
举报

相关推荐

0 条评论