XPath (XML Path Language) är ett uttrycksspråk för att välja noder från ett XML- eller HTML-dokument.
Testning
XPath Testbed
Testa och experimentera interaktivt med XPath-uttryck:
- XPath Testbed (whitebeam.org)
Webbläsarkonsol
$x("//div")
Tillgänglig direkt i utvecklarkonsolen för Chrome, Edge och Firefox.
Selektorer
Ättlingsselektorer
| CSS | XPath | Referens |
|---|---|---|
h1 |
//h1 |
? |
div p |
//div//p |
? |
ul > li |
//ul/li |
? |
ul > li > a |
//ul/li/a |
|
div > * |
//div/* |
|
:root |
/ |
? |
:root > body |
/body |
Attributselektorer
| CSS | XPath | Referens |
|---|---|---|
#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')] |
? |
Ordnings- & Indexselektorer
| CSS | XPath | Referens |
|---|---|---|
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"] |
Syskonelement
| CSS | XPath | Referens |
|---|---|---|
h1 ~ ul |
//h1/following-sibling::ul |
? |
h1 + ul |
//h1/following-sibling::ul[1] |
|
h1 ~ #id |
//h1/following-sibling::*[@id="id"] |
jQuery-motsvarigheter
| jQuery | XPath | Referens |
|---|---|---|
$('ul > li').parent() |
//ul/li/.. |
? |
$('li').closest('section') |
//li/ancestor-or-self::section |
|
$('a').attr('href') |
//a/@href |
? |
$('span').text() |
//span/text() |
Villkor & Logik
| Villkor | XPath | Referens |
|---|---|---|
h1:not([id]) |
//h1[not(@id)] |
? |
| Exakt textmatchning | //button[text()="Submit"] |
? |
| Delsträngsmatchning i text | //button[contains(text(),"Go")] |
|
| Aritmetiskt villkor | //product[@price > 2.50] |
|
| Har något barnelement | //ul[*] |
|
| Har ett specifikt barnelement | //ul[li] |
|
| 'OR'-logik | //a[@name or @href] |
? |
| Union (slå samman mängder) | //a | //div |
? |
Klasskontroll
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
XPath 1.0 saknar en operator för mellanslagsavgränsade token; denna standardmetod matchar hela klassnamn säkert.
Uttryck
Steg och axlar
Uppbyggnad av ett uttryck:
// |
ul |
/ |
a[@id='link'] |
|---|---|---|---|
| Axel | Steg | Axel | Steg |
Prefix
| Prefix | Exempel | Betydelse |
|---|---|---|
// |
//hr[@class='edge'] |
Var som helst i dokumentet |
./ |
./a |
Relativt nuvarande kontext |
/ |
/html/body/div |
Från rotelementet |
Uttryck kan börja med något av dessa prefix.
Axlar
| Axel | Exempel | Betydelse |
|---|---|---|
/ |
//ul/li/a |
Omedelbar barnnod |
// |
//*[@id="list"]//a |
Valfri ättlingsnod |
Steg separeras med /. Använd // för att matcha valfri djupnivå av ättlingar.
Steg
//div
//div[@name='box']
//*[@id='link']
Steg kan innehålla taggnamn och predikat ([...]). Båda är valfria. Steg kan även rikta in sig på nodvärden:
//a/text() #=> "Go home"
//a/@href #=> "index.html"
//a/* #=> All children of <a>
Predikat
Predikat
//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]
Filtrerar ned nodmängder när villkor uppfylls. Predikat kan kedjas direkt efter varandra.
Operatorer
# 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)]
Använda noder i predikat
# 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
Kedjad ordning
a[1][@href='/']
a[@href='/'][1]
Ordningen spelar roll: den första tar objekt 1 och kontrollerar dess href; den andra filtrerar på href först och väljer första träffen.
Nästlade predikat
//section[.//h1[@id='hi']]
Returnerar <section>-element som innehåller en <h1>-ättling med id='hi'.
Funktioner
Nodfunktioner
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]
Booleska funktioner
not(expr) # //button[not(starts-with(text(),"Submit"))]
Strängfunktioner
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()
Typkonvertering
string()
number()
boolean()
Axlar
Använda axlar
//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')
Axelsyntax:
// |
ul |
/child:: |
li |
|---|---|---|---|
| Axel | Steg | Axel | Steg |
Andra axlar
| Axel | Kortform | Beskrivning |
|---|---|---|
ancestor |
Förfaderselement | |
ancestor-or-self |
Kontextnod och dess förfäder | |
attribute |
@ |
@href är kortform för attribute::href |
child |
Standardaxel: div är child::div |
|
descendant |
Ättlingar | |
descendant-or-self |
// |
// är kortform för /descendant-or-self::node()/ |
namespace |
Namnrymdsnoder | |
self |
. |
. är kortform för self::node() |
parent |
.. |
.. är kortform för parent::node() |
following |
Allt efter sluttaggen | |
following-sibling |
Syskonnoder efter nuvarande | |
preceding |
Allt före öppningstaggen | |
preceding-sibling |
Syskonnoder före nuvarande |
Unioner
//a | //span
Använd | för att slå samman två eller flera nodmängder till en union.
Exempel
Vanliga frågemönster
//* # 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>
Hitta föräldraelement
//section[h1[@id='section-name']]
Hittar ett <section> som innehåller ett direkt barn h1#section-name.
//section[.//h1[@id='section-name']]
Hittar ett <section> som innehåller valfri ättling h1#section-name.