Xpath Operators in XML
XPath Operators in XML
What are XPath Operators?
XPath operators are used in XPath expressions to perform comparisons, arithmetic calculations, and logical operations.
They help filter and select nodes based on conditions.
Common XPath Operators
| Operator | Type | Description | Example Expression |
|---|---|---|---|
= | Comparison | Equals | /bookstore/book[@category='fiction'] |
!= | Comparison | Not equals | //book[@id != 'b1'] |
< | Comparison | Less than | //book[year < 2000] |
> | Comparison | Greater than | //book[year > 2000] |
<= | Comparison | Less than or equal to | //book[year <= 2005] |
>= | Comparison | Greater than or equal to | //book[year >= 2000] |
and | Logical | Logical AND | //book[@category='fiction' and year > 2000] |
or | Logical | Logical OR | //book[@category='fiction' or @category='history'] |
+ | Arithmetic | Addition | //book[price + 10 > 20] (if price exists) |
- | Arithmetic | Subtraction | //book[price - 5 < 30] |
* | Arithmetic | Multiplication | //book[price * 2 > 40] |
div | Arithmetic | Division | //book[price div 2 < 25] |
mod | Arithmetic | Modulus (remainder) | //book[price mod 5 = 0] |
| ` | ` | Union | Union of node sets |
Examples
Given this XML:
<books> <book category="fiction" price="15"> <title>The Hobbit</title> <year>1937</year> </book> <book category="history" price="25"> <title>Sapiens</title> <year>2011</year> </book></books>| XPath Expression | Meaning | Result |
|---|---|---|
//book[@category='fiction'] | Books with category fiction | The Hobbit book |
//book[price > 20] | Books with price greater than 20 | Sapiens book |
//book[price mod 5 = 0] | Books with price divisible by 5 | Both books |
//book[@category='fiction' and price < 20] | Fiction books priced under 20 | The Hobbit book |
| `//title | //year` | Select all <title> and <year> nodes |
Summary
XPath operators are essential for writing conditional queries.
They cover comparisons, logic, arithmetic, and node set unions.
Combining operators helps form complex XPath filters.
If you want, I can help you write XPath expressions using operators for your XML data!