XPath (XML Path Language) ist eine Ausdruckssprache zur Auswahl von Knoten aus einem XML- oder HTML-Dokument.
Testen
XPath Testbed
XPath-Ausdrücke interaktiv testen und ausprobieren:
- XPath Testbed (whitebeam.org)
Browser-Konsole
$x("//div")
Direkt verfügbar in den DevTools-Konsolen von Chrome, Edge und Firefox.
Selektoren
Nachfahren-Selektoren
| CSS | XPath | Referenz |
|---|---|---|
h1 |
//h1 |
? |
div p |
//div//p |
? |
ul > li |
//ul/li |
? |
ul > li > a |
//ul/li/a |
|
div > * |
//div/* |
|
:root |
/ |
? |
:root > body |
/body |
Attribut-Selektoren
| CSS | XPath | Referenz |
|---|---|---|
#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')] |
? |
Reihenfolge- & Index-Selektoren
| CSS | XPath | Referenz |
|---|---|---|
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"] |
Geschwisterelemente
| CSS | XPath | Referenz |
|---|---|---|
h1 ~ ul |
//h1/following-sibling::ul |
? |
h1 + ul |
//h1/following-sibling::ul[1] |
|
h1 ~ #id |
//h1/following-sibling::*[@id="id"] |
jQuery-Äquivalente
| jQuery | XPath | Referenz |
|---|---|---|
$('ul > li').parent() |
//ul/li/.. |
? |
$('li').closest('section') |
//li/ancestor-or-self::section |
|
$('a').attr('href') |
//a/@href |
? |
$('span').text() |
//span/text() |
Bedingungen & Logik
| Bedingung | XPath | Referenz |
|---|---|---|
h1:not([id]) |
//h1[not(@id)] |
? |
| Exakter Textabgleich | //button[text()="Submit"] |
? |
| Teilstring-Textabgleich | //button[contains(text(),"Go")] |
|
| Arithmetische Bedingung | //product[@price > 2.50] |
|
| Hat beliebiges Kindelement | //ul[*] |
|
| Hat bestimmtes Kindelement | //ul[li] |
|
| 'OR'-Logik | //a[@name or @href] |
? |
| Vereinigung (Mengen zusammenführen) | //a | //div |
? |
Klassenprüfung
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
XPath 1.0 hat keinen Operator für leerzeichengetrennte Token; dieser Standard-Workaround gleicht ganze Klassennamen sicher ab.
Ausdrücke
Schritte und Achsen
Aufbau eines Ausdrucks:
// |
ul |
/ |
a[@id='link'] |
|---|---|---|---|
| Achse | Schritt | Achse | Schritt |
Präfixe
| Präfix | Beispiel | Bedeutung |
|---|---|---|
// |
//hr[@class='edge'] |
Überall im Dokument |
./ |
./a |
Relativ zum aktuellen Kontext |
/ |
/html/body/div |
Vom Wurzelelement |
Ausdrücke können mit jedem dieser Präfixe beginnen.
Achsen
| Achse | Beispiel | Bedeutung |
|---|---|---|
/ |
//ul/li/a |
Direkter Kindknoten |
// |
//*[@id="list"]//a |
Beliebiger Nachfahrenknoten |
Schritte werden durch / getrennt. Verwende //, um beliebige Nachfahren-Ebenen abzugleichen.
Schritte
//div
//div[@name='box']
//*[@id='link']
Schritte können Tagnamen und Prädikate ([...]) enthalten. Beides ist optional. Schritte können auch Knotenwerte ansprechen:
//a/text() #=> "Go home"
//a/@href #=> "index.html"
//a/* #=> All children of <a>
Prädikate
Prädikate
//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]
Filtert Knotengruppen heraus, wenn Bedingungen zutreffen. Prädikate können direkt hintereinander verkettet werden.
Operatoren
# 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)]
Knoten in Prädikaten verwenden
# Inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
# Returns <ul> only if it has an <li> child
//ul[li]
Indizierung
//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
Verkettungsreihenfolge
a[1][@href='/']
a[@href='/'][1]
Die Reihenfolge zählt: Ersteres prüft beim ersten Element dessen href; Zweiteres filtert zuerst nach href und wählt den ersten Treffer.
Verschachtelte Prädikate
//section[.//h1[@id='hi']]
Gibt <section>-Elemente zurück, die ein Nachfahrenelement <h1> mit id='hi' enthalten.
Funktionen
Knotenfunktionen
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]
Boolesche Funktionen
not(expr) # //button[not(starts-with(text(),"Submit"))]
String-Funktionen
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()
Typkonvertierung
string()
number()
boolean()
Achsen
Achsen verwenden
//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')
Achsensyntax:
// |
ul |
/child:: |
li |
|---|---|---|---|
| Achse | Schritt | Achse | Schritt |
Weitere Achsen
| Achse | Kurzform | Beschreibung |
|---|---|---|
ancestor |
Vorfahren-Elemente | |
ancestor-or-self |
Kontextknoten und dessen Vorfahren | |
attribute |
@ |
@href ist Kurzform für attribute::href |
child |
Standardachse: div steht für child::div |
|
descendant |
Nachfahren | |
descendant-or-self |
// |
// ist Kurzform für /descendant-or-self::node()/ |
namespace |
Namensraum-Knoten | |
self |
. |
. ist Kurzform für self::node() |
parent |
.. |
.. ist Kurzform für parent::node() |
following |
Alles nach dem schließenden Tag | |
following-sibling |
Geschwisterknoten nach dem aktuellen Element | |
preceding |
Alles vor dem öffnenden Tag | |
preceding-sibling |
Geschwisterknoten vor dem aktuellen Element |
Vereinigungen
//a | //span
Verwende |, um zwei oder mehr Knotengruppen zu einer Vereinigungsmenge zusammenzuführen.
Beispiele
Häufige Abfragemuster
//* # 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>
Elternelemente finden
//section[h1[@id='section-name']]
Findet ein <section>, das ein direktes Kind h1#section-name enthält.
//section[.//h1[@id='section-name']]
Findet ein <section>, das ein beliebiges Nachfahrenelement h1#section-name enthält.