XPath (XML Path Language) is een expressietaal voor het selecteren van knopen uit een XML- of HTML-document.
Testen
XPath Testbed
Test en experimenteer interactief met XPath-expressies:
- XPath Testbed (whitebeam.org)
Browserconsole
$x("//div")
Direct beschikbaar in de DevTools-consoles van Chrome, Edge en Firefox.
Selectors
Afstammelingsselectors
| CSS | XPath | Referentie |
|---|---|---|
h1 |
//h1 |
? |
div p |
//div//p |
? |
ul > li |
//ul/li |
? |
ul > li > a |
//ul/li/a |
|
div > * |
//div/* |
|
:root |
/ |
? |
:root > body |
/body |
Attribuutselectors
| CSS | XPath | Referentie |
|---|---|---|
#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')] |
? |
Volgorde- & Indexselectors
| CSS | XPath | Referentie |
|---|---|---|
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"] |
Zusterelementen
| CSS | XPath | Referentie |
|---|---|---|
h1 ~ ul |
//h1/following-sibling::ul |
? |
h1 + ul |
//h1/following-sibling::ul[1] |
|
h1 ~ #id |
//h1/following-sibling::*[@id="id"] |
jQuery-equivalenten
| jQuery | XPath | Referentie |
|---|---|---|
$('ul > li').parent() |
//ul/li/.. |
? |
$('li').closest('section') |
//li/ancestor-or-self::section |
|
$('a').attr('href') |
//a/@href |
? |
$('span').text() |
//span/text() |
Voorwaarden & Logica
| Voorwaarde | XPath | Referentie |
|---|---|---|
h1:not([id]) |
//h1[not(@id)] |
? |
| Exacte tekstovereenkomst | //button[text()="Submit"] |
? |
| Gedeeltelijke tekstovereenkomst | //button[contains(text(),"Go")] |
|
| Rekenkundige voorwaarde | //product[@price > 2.50] |
|
| Heeft een willekeurig kindelement | //ul[*] |
|
| Heeft een specifiek kindelement | //ul[li] |
|
| 'OR'-logica | //a[@name or @href] |
? |
| Vereniging (verzamelingen samenvoegen) | //a | //div |
? |
Klassecontrole
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
XPath 1.0 mist een operator voor spatiegescheiden tokens; deze standaardmethode vergelijkt veilige volledige klassenamen.
Expressies
Stappen en assen
Anatomie van een expressie:
// |
ul |
/ |
a[@id='link'] |
|---|---|---|---|
| As | Stap | As | Stap |
Voorvoegsels
| Voorvoegsel | Voorbeeld | Betekenis |
|---|---|---|
// |
//hr[@class='edge'] |
Overal in het document |
./ |
./a |
Relatief ten opzichte van huidige context |
/ |
/html/body/div |
Vanaf het hoofdelement |
Expressies kunnen met elk van deze voorvoegsels beginnen.
Assen
| As | Voorbeeld | Betekenis |
|---|---|---|
/ |
//ul/li/a |
Direct kindknoop |
// |
//*[@id="list"]//a |
Elke afstammingsknoop |
Stappen worden gescheiden door /. Gebruik // om elk afstammelingsniveau te matchen.
Stappen
//div
//div[@name='box']
//*[@id='link']
Stappen kunnen tagnamen en predicaten ([...]) bevatten. Beide zijn optioneel. Stappen kunnen ook knoopwaarden selecteren:
//a/text() #=> "Go home"
//a/@href #=> "index.html"
//a/* #=> All children of <a>
Predicaten
Predicaten
//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]
Filtert knoopverzamelingen wanneer voorwaarden overeenkomen. Predicaten kunnen achter elkaar worden geschakeld.
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)]
Knopen gebruiken in predicaten
# Inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
# Returns <ul> only if it has an <li> child
//ul[li]
Indexering
//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
Gekoppelde volgorde
a[1][@href='/']
a[@href='/'][1]
De volgorde doet ertoe: de eerste neemt item 1 en controleert de href; de tweede filtert eerst op href en kiest de eerste match.
Geneste predicaten
//section[.//h1[@id='hi']]
Retourneert <section>-elementen die een <h1>-afstammeling met id='hi' bevatten.
Functies
Knoopfuncties
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]
Booleaanse functies
not(expr) # //button[not(starts-with(text(),"Submit"))]
Tekenreeksfuncties
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()
Typeconversie
string()
number()
boolean()
Assen
Assen gebruiken
//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')
Assyntaxis:
// |
ul |
/child:: |
li |
|---|---|---|---|
| As | Stap | As | Stap |
Overige assen
| As | Korte vorm | Beschrijving |
|---|---|---|
ancestor |
Voorouderelementen | |
ancestor-or-self |
Contextknoop en zijn voorouders | |
attribute |
@ |
@href is afkorting voor attribute::href |
child |
Standaardas: div is child::div |
|
descendant |
Afstammelingen | |
descendant-or-self |
// |
// is afkorting voor /descendant-or-self::node()/ |
namespace |
Naamruimteknopen | |
self |
. |
. is afkorting voor self::node() |
parent |
.. |
.. is afkorting voor parent::node() |
following |
Alles na de sluittag | |
following-sibling |
Zusterknopen na de huidige | |
preceding |
Alles vóór de openingstag | |
preceding-sibling |
Zusterknopen vóór de huidige |
Verenigingen (Unions)
//a | //span
Gebruik | om twee of meer knoopverzamelingen samen te voegen tot een vereniging.
Voorbeelden
Veelgebruikte querypatronen
//* # 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>
Bovenliggende elementen vinden
//section[h1[@id='section-name']]
Vindt een <section> met een direct kind h1#section-name.
//section[.//h1[@id='section-name']]
Vindt een <section> met een willekeurige afstammeling h1#section-name.