觀念
XPath 是 W3C 標準,專門用於在 XML 文件中導覽、尋找節點,是 XSLT 的核心基礎;XSLT 裡 select=""、test="" 內部的運算式全部都使用 XPath。
- 透過路徑運算式定位節點
- 內建超過100個標準函式:字串、數值、日期比對、節點處理、邏輯運算等
7種節點類型
文件節點(根節點)、元素節點、屬性節點、文字節點、註解節點、處理指令節點、命名空間節點。
範例:
<title lang="eng">Harry Potter</title>
<title>→ 元素節點lang="eng"→ 屬性節點Harry Potter→ 文字節點
觀念
- 基本值(原子值 Atomic value):沒有子節點、沒有父節點的節點內容,例如
eng、29.99 - 項目(Item):項目 = 節點 或者 基本值
XML節點之間的關係
以 <bookstore><book><title></title></book></bookstore> 作為範例
- 父(Parent):每個元素、屬性都只有一個父節點;
book是title的父節點 - 子(Children):元素可以擁有多個子節點;
title、price是book的子節點 - 同層(Sibling):擁有同一個父節點;同一層級的title、price互為同層節點
- 祖先(Ancestor):父、父的父,往上所有層級;
title的祖先:book、bookstore
路徑運算式
透過路徑/步驟選取XML節點
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
</bookstore>Code language: HTML, XML (xml)
| 運算式 | 含義 |
|---|---|
bookstore | 選取根底下的 bookstore 元素 |
/bookstore | 絕對路徑,從根節點開始比對 |
bookstore/book | 選取bookstore底下所有book子元素 |
//book | 文件所有位置的book元素(全域搜尋) |
//@lang | 選取所有名稱為lang的屬性節點 |
XPath 函式:position()
<xsl:value-of select="position()" />Code language: HTML, XML (xml)
position()是XPath內建函式,用來取得當前遍歷節點在節點集合裡的序號,從1開始計數。
範例,輸出序號
<?xml version="1.0" encoding="gb2312"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head></head>
<body>
<ul>
<!--遍歷所有學生 class/student -->
<xsl:for-each select="class/student">
<xsl:sort select="age"/> <!--依照年齡升序排序-->
<!--篩選身高>160的學生-->
<xsl:if test="height > 160">
<li>
<xsl:value-of select="position()" />、<!--輸出序號-->
<xsl:value-of select="name"/>;
<!--多重條件判斷-->
<xsl:choose>
<xsl:when test="height > 200">
<b><xsl:value-of select="age"/></b>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="age"/>
</xsl:otherwise>
</xsl:choose>
</li>
</xsl:if>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>Code language: HTML, XML (xml)
XPath