Cover Image for XPath Syntax
105 views

XPath Syntax

XPath (XML Path Language) is a language used to navigate and select nodes in XML or HTML documents. It allows you to specify patterns and conditions to identify specific elements, attributes, or other parts of the document’s structure. XPath expressions are written as strings and can be used in various contexts, such as XSLT, XML parsing, and web scraping.

Here is the basic syntax of XPath expressions:

  1. Node Selection:
  • nodename: Selects all elements with the name “nodename.”
  • /: Selects from the root node.
  • //: Selects nodes from anywhere in the document.
  • .: Selects the current node.
  • ..: Selects the parent of the current node.
  1. Predicates:
  • [condition]: Filters nodes based on the condition inside the square brackets.
  1. Axes:
  • axis::nodename: Specifies a node’s relationship with another node using an axis.
  1. Attributes:
  • @attribute: Selects the value of an attribute.
  1. Functions:
  • function(): Invokes XPath functions to perform operations or retrieve values.
  1. Operators:
  • =: Equal to.
  • !=: Not equal to.
  • <: Less than.
  • >: Greater than.
  • <=: Less than or equal to.
  • >=: Greater than or equal to.
  • and: Logical AND.
  • or: Logical OR.
  • not(): Logical NOT.

Here are some examples of XPath expressions:

  • //book: Selects all <book> elements in the entire document.
  • /bookstore/book: Selects all <book> elements that are children of the <bookstore> element.
  • //book/author: Selects all <author> elements that are children of <book> elements anywhere in the document.
  • //book[@category='fiction']: Selects all <book> elements that have a “category” attribute with the value “fiction.”
  • //book[position() <= 3]: Selects the first three <book> elements in the document.
  • //book[price > 20 and @lang='en']: Selects all <book> elements with a “price” greater than 20 and a “lang” attribute with the value “en.”

XPath syntax allows for powerful and flexible querying of XML and HTML documents, making it a valuable tool for data extraction and manipulation. The expressions can be combined and refined to precisely target the nodes and data you need.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS