クイックリファレンス

XPath チートシート

XPath 1.0/2.0 の総合リファレンス:CSS とのセレクタ対比、軸(Axes)、述語(Predicates)、各種関数、ノード走査式を網羅。

· 公開日

XPath(XML Path Language)は、XML または HTML ドキュメントからノードを選択するための式言語です。

テスト

XPath テストベッド

XPath 式を対話的にテスト・検証できます:

ブラウザコンソール

$x("//div")

Chrome、Edge、Firefox の DevTools コンソール内でそのまま利用できます。

セレクタ

子孫セレクタ

CSS XPath 参照
h1 //h1 ?
div p //div//p ?
ul > li //ul/li ?
ul > li > a //ul/li/a
div > * //div/*
:root / ?
:root > body /body

属性セレクタ

CSS XPath 参照
#id //*[@id="id"] ?
.class //*[@class="class"] ?
input[type="submit"] //input[@type="submit"]
a#abc[for="xyz"] //a[@id="abc"][@for="xyz"] ?
a[rel] //a[@rel]
a[href^='/'] //a[starts-with(@href, '/')] ?
a[href$='pdf'] //a[ends-with(@href, '.pdf')]
a[href*='://'] //a[contains(@href, '://')]
a[rel~='help'] //a[contains(@rel, 'help')] ?

順序とインデックスセレクタ

CSS XPath 参照
ul > li:first-of-type //ul/li[1] ?
ul > li:nth-of-type(2) //ul/li[2]
ul > li:last-of-type //ul/li[last()]
li#id:first-of-type //li[1][@id="id"] ?
a:first-child //*[1][name()="a"]
a:last-child //*[last()][name()="a"]

兄弟要素

CSS XPath 参照
h1 ~ ul //h1/following-sibling::ul ?
h1 + ul //h1/following-sibling::ul[1]
h1 ~ #id //h1/following-sibling::*[@id="id"]

jQuery との対応

jQuery XPath 参照
$('ul > li').parent() //ul/li/.. ?
$('li').closest('section') //li/ancestor-or-self::section
$('a').attr('href') //a/@href ?
$('span').text() //span/text()

条件と論理

条件 XPath 参照
h1:not([id]) //h1[not(@id)] ?
テキストの完全一致 //button[text()="Submit"] ?
テキストの部分一致 //button[contains(text(),"Go")]
算術条件 //product[@price > 2.50]
任意の子要素を持つ //ul[*]
特定の子要素を持つ //ul[li]
OR 論理和 //a[@name or @href] ?
和集合(セットを結合) //a | //div ?

クラス名の判定

//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]

XPath 1.0 には空白区切りトークンに一致する演算子がないため、この定番手法でクラス名全体を一意に照合します。

式

ステップと軸

式の構造:

// ul / a[@id='link']
軸 ステップ 軸 ステップ

接頭辞

接頭辞 例 意味
// //hr[@class='edge'] ドキュメント内の任意の場所
./ ./a 現在のコンテキストに対する相対位置
/ /html/body/div ルート要素から

式はこれらの接頭辞のいずれからでも始めることができます。

軸

軸 例 意味
/ //ul/li/a 直下の子ノード
// //*[@id="list"]//a 任意の子孫ノード

ステップは / で区切ります。任意の子孫レベルに一致させるには // を使用します。

ステップ

//div
//div[@name='box']
//*[@id='link']

ステップにはタグ名と述語([...])を含めることができ、どちらも省略可能です。ノードの値を対象にすることもできます:

//a/text()     #=> "Go home"
//a/@href      #=> "index.html"
//a/*          #=> All children of <a>

述語 (Predicates)

述語 (Predicates)

//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]

条件に一致したときにノード集合を絞り込みます。述語は連続して連結できます。

演算子

# Comparison
//a[@id = "xyz"]
//a[@id != "xyz"]
//a[@price > 25]
# Logic (and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]

述語内でのノード指定

# Inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
# Returns <ul> only if it has an <li> child
//ul[li]

インデックス指定

//a[1]                  # First <a> (1-based index)
//a[last()]             # Last <a>
//ol/li[2]              # Second <li>
//ol/li[position()=2]   # Same as above
//ol/li[position()>1]   # All except the first

連結の順序

a[1][@href='/']
a[@href='/'][1]

順序が重要です。前者は最初の要素を取得してから href を確認し、後者はまず href で絞り込んでから最初の一致を選択します。

ネストした述語

//section[.//h1[@id='hi']]

id='hi' を持つ <h1> 子孫要素を含む <section> 要素を返します。

関数

ノード関数

name()                     # Starts with: //[starts-with(name(), 'h')]
text()                     # Exact match: //button[text()="Submit"]
                           # Value: //button/text()
lang(str)
namespace-uri()
count()                    # //table[count(tr)=1]
position()                 # //ol/li[position()=2]

論理関数

not(expr)                  # //button[not(starts-with(text(),"Submit"))]

文字列関数

contains()                 # //span[contains(@class,"head")]
starts-with()              # //span[starts-with(@class,"head")]
ends-with()                # //span[ends-with(@class,"head")]
concat(x, y)
substring(str, start, len)
substring-before("01/02", "/")  #=> "01"
substring-after("01/02", "/")   #=> "02"
translate()
normalize-space()
string-length()

型変換

string()
number()
boolean()

軸

軸の使用例

//ul/li                       # ul > li
//ul/child::li                # ul > li (explicit child axis)
//ul/following-sibling::li    # ul ~ li
//ul/descendant-or-self::li   # ul li
//ul/ancestor-or-self::li     # $('ul').closest('li')

軸の構文:

// ul /child:: li
軸 ステップ 軸 ステップ

その他の軸

軸 省略記法 説明
ancestor 祖先要素
ancestor-or-self コンテキストノードとその祖先
attribute @ @href は attribute::href の省略形
child デフォルト軸:div は child::div と同義
descendant 子孫
descendant-or-self // // は /descendant-or-self::node()/ の省略形
namespace 名前空間ノード
self . . は self::node() の省略形
parent .. .. は parent::node() の省略形
following 終了タグの後ろにあるすべて
following-sibling 現在の要素の後ろにある兄弟ノード
preceding 開始タグの前にあるすべて
preceding-sibling 現在の要素の前にある兄弟ノード

和集合(Unions)

//a | //span

2 つ以上のノード集合を和集合に結合するには | を使用します。

実例

よく使われるクエリパターン

//*                 # All elements
count(//*)          # Count all elements
(//h1)[1]/text()    # Text of the very first h1 heading in document
//li[span]          # Find <li> containing a <span> child
//ul/li/..          # Navigate back to parent <ul>

親要素の検索

//section[h1[@id='section-name']]

直接の子要素 h1#section-name を含む <section> を検索します。

//section[.//h1[@id='section-name']]

任意の子孫要素 h1#section-name を含む <section> を検索します。

関連テーマ