XPath

XPath

Syntex

Expression Description
nodename 選取所有 name 為 nodename 的節點
/

選取自 current node 的下一層

‘/’ 表示 root
故以 ‘/’ 開頭的路徑為絕對路徑

// 選取 current node 下所有符合條件的節點
. 選取 current node
.. 選取 current node 的 parent node
@ 選取 attributes

Predicates

Path Expression Result
/bookstore/book[1] bookstore → 第 1 個 book
註:IE 5/6/7/8/9 的第 1 個元素是 [0]
/bookstore/book[last()]

bookstore → 最後一個 book

/bookstore/book[last()-1] bookstore → 最後一個的前 1 個 book
/bookstore/book[position()<3] bookstore → 前 2 個 books

//title[@lang]
 title[@lang]

選取所有有 ‘lang’ attribute 的 titles
//title[@lang=’en’] 選取所有 ‘lang’ attribute 為 ‘en’ 的 titles
/bookstore/book[price>35.00] bookstore → 有 ‘price’ element 且其 value 大於 35.00 的books
/bookstore/book[price>35.00]/title bookstore → 有 ‘price’ element 且其 value 大於 35.00 的books → 前者其下的所有titles
…/a/@href … → a 的 ‘href’ attribute
…/a[@href]/text() <a href=”…”>{text}</a>

Selecting Unknown Nodes

Wildcard  Description
* 任意 element node
@*

任意 attribute node

node() 任意 node

用 Chrome 找出 XPath

右鍵 → 檢查開啟Chrome DevTools
在 Elements 下找到想要的 HTML Element
右鍵 → Copy→ Copy XPath

Ref

https://www.w3schools.com/xml/xpath_intro.asp

Last Updated on 2023/08/16 by A1go

目錄
Bitnami