Improve xpath

This commit is contained in:
Rico Sta. Cruz 2015-04-17 14:17:43 +08:00
parent 5badb60ca2
commit d9e91c91d3
1 changed files with 105 additions and 64 deletions

139
xpath.md
View File

@ -6,33 +6,35 @@ layout: default
CSS equivalents CSS equivalents
--------------- ---------------
| CSS | Xpath | | CSS | Xpath | ? |
| --- | --- | | --- | --- | ---: |
| `div p` | `//div//p` | | `ul > li` | `//ul/li` | [?](#axes) |
| `ul > li` | `//ul/li` | | `div > *` | `//div/*` | |
| `div > *` | `//div/*` | | --- | --- | |
| `h1 ~ ul` | `//h1/following-sibling::ul` | | `div p` | `//div//p` | [?](#axes) |
| `h1 ~ #id` | `//h1/following-sibling::[@id="id"]` | | --- | --- | |
| --- | --- | | `h1 ~ ul` | `//h1/following-sibling::ul` | [?](#other-axes) |
| `:root` | `/` | | `h1 ~ #id` | `//h1/following-sibling::[@id="id"]` | |
| `:root > body` | `/body` | | --- | --- | |
| --- | --- | | `:root` | `/` | [?](#prefixes) |
| `input[type="submit"]` | `//input[@type="submit"]` | | `:root > body` | `/body` | |
| `a[href^='/']` | `//a[starts-with(@href, '/')]` | | --- | --- | |
| `a[href$='pdf']` | `//a[ends-with(@href, '.pdf')]` | | `input[type="submit"]` | `//input[@type="submit"]` | [?](#predicates) |
| --- | --- | | `a[href^='/']` | `//a[starts-with(@href, '/')]` | [?](#string-functions) |
| `#id` | `//[@id="id"]` | | `a[href$='pdf']` | `//a[ends-with(@href, '.pdf')]` | |
| `.class` | `//[@class="class"]` *...see below* | | --- | --- | |
| --- | --- | | `#id` | `//[@id="id"]` | |
| `ul > li:first-child` | `//ul/li[1]` | | `.class` | `//[@class="class"]` *...see below* | |
| `ul > li:nth-child(2)` | `//ul/li[2]` | | --- | --- | |
| `ul > li:last-child` | `//ul/li[last()]` | | `ul > li:first-child` | `//ul/li[1]` | [?](#indexing) |
| --- | --- | | `ul > li:nth-child(2)` | `//ul/li[2]` | |
| `li#id:first-child` | `//li[@id="id"][1]` | | `ul > li:last-child` | `//ul/li[last()]` | |
| --- | --- | | --- | --- | |
| `a:first-child` | `//a[1]` | | `li#id:first-child` | `//li[@id="id"][1]` | [?](#chaining-order) |
| `a:last-child` | `//a[last()]` | | --- | --- | |
| `li:first-of-type` | `//li[not(preceding-sibling::li)]` | | `a:first-child` | `//a[1]` | |
| `a:last-child` | `//a[last()]` | |
| `li:first-of-type` | `//li[not(preceding-sibling::li)]` | |
{:.greycode.no-head} {:.greycode.no-head}
### Class check ### Class check
@ -42,15 +44,22 @@ Xpath doesn't have the "check if part of space-separated list" operator, so this
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')] //div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
``` ```
### jQuery equivalents ### Other stuff
For things that CSS alone can't do. For things that CSS alone can't do.
| jQuery | Xpath | | jQuery | Xpath |
| ------ | --- | | ------ | --- |
| `$('ul > li').parent()` | `//ul/li/..` | | `$('ul > li').parent()` | `//ul/li/..` |
| `$('li').closest('section')` | `//li/ancestor-or-self::section` | | `$('li').closest('section')` | `//li/ancestor-or-self::section` |
| ---- | ---- |
| `$('a').attr('href')` | `//a/@href` | | `$('a').attr('href')` | `//a/@href` |
| `$('span').text()` | `//span/text()` | | `$('span').text()` | `//span/text()` |
| ---- | ---- |
| Text match | `//button[text()="Submit"]` |
| Text match (substring) | `//button[contains(text(),"Go")]` |
| Arithmetic | `//product[@price > 2.50]` |
| Has children | `//ul[*]` |
| Has children (specific) | `//ul[li]` |
{:.greycode.no-head} {:.greycode.no-head}
@ -68,7 +77,7 @@ Begin your expression with any of these.
{:.greycode.no-head} {:.greycode.no-head}
### Axes ### Axes
Separate your steps with `/`. Use two (`//`) if you don't want direct descendants. Separate your steps with `/`. Use two (`//`) if you don't want to select direct children.
| Axis | Example | | Axis | Example |
| --- | --- | | --- | --- |
@ -76,10 +85,18 @@ Separate your steps with `/`. Use two (`//`) if you don't want direct descendant
| `//` *descendant* | `//[@id="list"]//a` | | `//` *descendant* | `//[@id="list"]//a` |
{:.greycode.no-head} {:.greycode.no-head}
### Selecting node data ### Steps
A step may have an element name (`div`) and [predicates](#predicate) (`[...]`). Both are optional.
```sh
//div
//div[@name='box']
//[@id='link']
```
They can also be these other things.
```sh ```sh
//a #=> <a>
//a/text() #=> "Go home" //a/text() #=> "Go home"
//a/@href #=> "index.html" //a/@href #=> "index.html"
//a/* #=> All a's child elements //a/* #=> All a's child elements
@ -88,7 +105,7 @@ Separate your steps with `/`. Use two (`//`) if you don't want direct descendant
Predicates Predicates
---------- ----------
### Predicates (`[]`) ### Predicates (`[...]`)
Restricts a nodeset only if some condition is true. They can be chained. Restricts a nodeset only if some condition is true. They can be chained.
```sh ```sh
@ -98,7 +115,7 @@ Restricts a nodeset only if some condition is true. They can be chained.
``` ```
### Operators ### Operators
Use operators to make conditionals. Use comparison and logic operators to make conditionals.
```sh ```sh
# Comparison # Comparison
@ -134,10 +151,11 @@ Use `[]` with a number, or `last()` or `position()`.
//a[1] # first <a> //a[1] # first <a>
//a[last()] # last <a> //a[last()] # last <a>
//ol/li[2] # second <li> //ol/li[2] # second <li>
//ol/li[position()=2] # ...same as above //ol/li[position()=2] # same as above
//ol/li[position()>1] # :not(:first-child)
``` ```
### Predicate order ### Chaining order
Order is significant, these two are different. Order is significant, these two are different.
```sh ```sh
@ -172,7 +190,7 @@ position() # //ol/li[position()=2]
### Boolean functions ### Boolean functions
```sh ```sh
not(expr) # button[not(text()="Submit")] not(expr) # button[not(starts-with(text(),"Submit"))]
``` ```
### String functions ### String functions
@ -202,38 +220,61 @@ boolean()
Axes Axes
---- ----
### The / separator
Steps of an expression are separated by `/`, usually used to pick child nodes. That's not always true: you can specify a different "axis" with `::`.
```sh ```sh
//ul/li //ul/li # $('ul > li')
//div/h1/span //ul/ancestor-or-self::li # $('ul').closest('li')
``` ```
{:.light} {:.light}
### Descendant-or-self axis ### Descendant-or-self axis
When you use `//` for descendants, this is short or `/descendant-or-self::`. When you use `//` for descendants, this is short for the `descendant-or-self::` axis.
```sh ```sh
# both the same
//div//h4 //div//h4
//div/descendant-or-self::h4 //div/descendant-or-self::h4
```
```sh
# both the same
//ul//[last()] //ul//[last()]
//ul/descendant-or-self::[last()] //ul/descendant-or-self::[last()]
``` ```
### Child axis ### Child axis
When no axis is specifid, a step with a `name` is short for `child::name`. This is what makes `//a/b/c` work. When axis is not specified, a `name` is short for `child::name`. This is what makes `//a/b/c` work.
```sh ```sh
# both the same
//ul/li/a //ul/li/a
//ul/child::li/child::a //child::ul/child::li/child::a
```
```sh
# both the same
# this works because `child::li` is truthy, so the predicate succeeds
//ul[li]
//ul[child::li]
```
```sh
# both the same
//ul[count(li) > 2]
//ul[count(child::li) > 2]
``` ```
### Attribute axis ### Attribute axis
When you use `@` for attributes, that's short for the `attribute::` axis. When you use `@` for attributes, that's short for the `attribute::` axis.
```sh ```sh
# both the same
//a/@href //a/@href
//a/attribute::href //a/attribute::href
# both the same
//div[@id="box"] //div[@id="box"]
//div[attribute::id="box"] //div[attribute::id="box"]
``` ```
@ -267,20 +308,15 @@ More examples
```sh ```sh
//* # all elements //* # all elements
count(//*) # count all elements count(//*) # count all elements
//h1[1]/text() # hext of the first h1 heading //h1[1]/text() # text of the first h1 heading
//li[span] # Find a <li> with an <span> inside it //li[span] # find a <li> with an <span> inside it
# ...expands to //li[child::span] # ...expands to //li[child::span]
//ul/li/.. # use .. to select a parent //ul/li/.. # use .. to select a parent
``` ```
```sh ```sh
# Find a <section> that directly contains h1#section-name # Find a <section> that directly contains h1#section-name
//section[child::h1[@id='section-name']] //section[h1[@id='section-name']]
```
```sh
# like jQuery's $().closest('.box')
./ancestor-or-self::[@class="box"]
``` ```
```sh ```sh
@ -289,6 +325,11 @@ count(//*) # count all elements
//section[//*[@id='section-name']] //section[//*[@id='section-name']]
``` ```
```sh
# like jQuery's $().closest('.box')
./ancestor-or-self::[@class="box"]
```
```sh ```sh
# Find <item> and check its attributes # Find <item> and check its attributes
//item[@price > 2*@discount] //item[@price > 2*@discount]