Cover Image for XPath Operators
103 views

XPath Operators

XPath supports several operators that allow you to perform various operations and comparisons when navigating and selecting nodes within XML or HTML documents. Here are the most commonly used XPath operators:

  1. // (Double Slash):
  • Example: //book
  • Selects all <book> elements in the entire document.
  1. / (Single Slash):
  • Example: /bookstore/book
  • Selects all <book> elements that are children of the <bookstore> element.
  1. @ (At-sign):
  • Example: //bookstore/@location
  • Selects the “location” attribute of the <bookstore> element.
  1. | (Pipe):
  • Example: //book | //cd
  • Selects all <book> and <cd> elements in the entire document.
  1. text():
  • Example: //book[text()='Harry Potter']
  • Selects all <book> elements that have the exact text “Harry Potter.”
  1. not():
  • Example: //book[not(price > 20)]
  • Selects all <book> elements that do not have a child element named “price” with a value greater than 20.
  1. and:
  • Example: //book[price > 20 and @category='fiction']
  • Selects all <book> elements that have both a child element named “price” with a value greater than 20 and a “category” attribute with the value “fiction.”
  1. or:
  • Example: //book[@category='fiction' or @category='fantasy']
  • Selects all <book> elements that have a “category” attribute with either “fiction” or “fantasy.”
  1. = (Equal to), != (Not equal to), < (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to):
  • Example: //book[price > 10]
  • Selects all <book> elements that have a child element named “price” with a value greater than 10.
  1. contains(), starts-with(), ends-with():
  • Example: //book[contains(title, 'Potter')]
  • Selects all <book> elements that have a child element named “title” containing the substring “Potter” in their text.

XPath operators are essential for creating expressive and powerful expressions to filter, navigate, and select specific nodes within XML or HTML documents. By combining these operators with element names, attributes, strings, and numeric values, you can build complex queries to retrieve precisely the data you need from the document.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS