- 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>
驗證輸出
廣告