XPath (XML Path Language) is an expression language designed to support the query or transformation of XML documents. It can be used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML document. Support for XPath exists in applications that support XML, such as web browsers and many programming languages.
XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or steps.
Expression | Description |
---|---|
nodename | Selects all nodes with the name "nodename" |
/ | Selects from the root node |
// | Selects nodes in the document from the current node that match the selection no matter where they are |
. | Selects the current node |
.. | Selects the parent of the current node |
@ | Selects attributes |
The XPath expression selects nodes or a list of nodes based on attributes like ID, Name, Classname, etc., from an XML document.
//input[@name = 'value']
input
= tag namename
= attributevalue
= value of attributeThe Contains()
is a method that is used to find the value of those attribute that changes dynamically.
The Contains()
method has the following general form, which is given below.
XPath Contains Syntax:
XPath = //tagname[contains(@attribute, 'value')]
The main feature of contains() method is that it can find elements with partial text.
It is a common mistake to use it to test if an element contains a value. What it really does is test if a string contains a substring.
starts-with()
is a method that checks the starting text of an attribute and finds elements whose attribute changes dynamically.
We can also use this method to find elements whose attribute value is static (not changing).
The syntax for starts-with():
XPath = //tagname[starts-with(@attribute, 'value')]
The ends-with()
method checks the ending text of an attribute and finds elements whose attribute changes dynamically.
Syntax of ends-with()
:
//tagname[ends-with(@attribute, 'value')]
In an OR expression, two conditions are used, and any one condition, either 1st condition or 2nd condition, should be true to find the elements.
It has the following syntax:
//tagname[XPath statement-1 or XPath statement-2]
In an AND expression, two conditions are used, and both conditions must be true to find the elements. If any condition is false
then XPath will be failed to find the element. It has the following general form.
//tagname[XPath statement-1 and XPath statement-2]
The text()
method is used to find elements with an exact match.
The syntax for the text()
method is given below:
//tagname[text() = 'text_value']
The normalize-space()
function returns the argument string with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of whitespace characters with a single space.
//tagname[normalize-space()='value']