- XPath 教程
- XPath - 首页
- XPath - 概述
- XPath - 表达式
- XPath - 节点
- XPath - 绝对路径
- XPath - 相对路径
- XPath - 轴
- XPath - 运算符
- XPath - 通配符
- XPath - 谓词
- XPath 有用资源
- XPath - 快速指南
- XPath - 有用资源
- XPath - 讨论
XPath - 轴
就像位置路径使用绝对或相对路径定义节点的位置一样,轴用于通过其关系(如**父、子、兄弟**等)来识别元素。轴之所以如此命名,是因为它们指的是元素相对于某个元素所在的轴线。
以下是各种轴值的列表。
| 序号 | 轴 & 描述 |
|---|---|
| 1 | ancestor 表示当前节点的祖先,包括从父节点到根节点的所有父节点。 |
| 2 | ancestor-or-self 表示当前节点及其祖先。 |
| 3 | attribute 表示当前节点的属性。 |
| 4 | child 表示当前节点的子节点。 |
| 5 | descendant 表示当前节点的后代。后代包括节点的子节点,直到叶子节点(没有更多子节点)。 |
| 6 | descendant-or-self 表示当前节点及其后代。 |
| 7 | following 表示出现在当前节点之后的所有节点。 |
| 8 | following-sibling 表示上下文节点之后的兄弟节点。兄弟节点与当前节点处于同一级别,并共享其父节点。 |
| 9 | namespace 表示当前节点的命名空间。 |
| 10 | parent 表示当前节点的父节点。 |
| 11 | preceding 表示出现在当前节点之前的所有节点(即其开始标签之前)。 |
| 12 | self 表示当前节点。 |
以下是一些关于轴用法示例。
firstname - 选择与学生节点相关的 firstname。
<p><xsl:value-of select = "firstname"/></p> <xsl:value-of select = "/class/student/preceding-sibling::comment()"/>
示例
在此示例中,我们创建了一个示例 XML 文档**students.xml**及其样式表文档**students.xsl**,该文档使用 XPath 表达式。
以下是使用的示例 XML。
students.xml
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
<!-- Comment: This is a list of student -->
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
students.xsl
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/" >
<html>
<body>
<xsl:value-of select = "/class/student/preceding-sibling::comment()"/>
<br/>
<xsl:text>First Student: </xsl:text>
<xsl:value-of select = "/class/student/child::firstname" />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
验证输出
广告