How to use of XPath Predicates in XML
In this article I will explain the predicates in XPath.
Introduction
Predicates are used to find a specific node/element or a node that contains a specific value.Predicates are always embedded in square brackets,like inside [ ].The following are some path expressions with predicates and the result of the expressions based on the below example,
Example
<?xml version="1.0" encoding="utf-8" ?>
<Employee>
<Trainee>
<Name>Harry</Name>
<id>1234</id>
<Salary>10k</Salary>
<address street="12">Delhi</address>
</Trainee>
<Trainee>
<Name>Georage</Name>
<id>1432</id>
<Salary>20k</Salary>
<address street="10">Delhi</address>
</Trainee>
</Employee>
|
Now the following lines shows that how the nodes of above example represents the path expressions of predicates.
-
/Employee/Trainee[1] : Selects the first Trainee element that is the child of the Employee element.
-
/Employee/Trainee[last()] : Selects the last Trainee element that is the child of the Employee element.
-
/Employee/Trainee[last()-1] : Selects the last but one Trainee element that is the child of the Employee element.
-
/Employee/Trainee[position()<3] : Selects the first two Trainee elements that are children of the Employee element.
-
//address[@street] : Selects all the address elements that have an attribute named street.
-
//address[@street="12"] : Selects all the address elements that have an attribute named street with a value of "12".
-
/Employee/Trainee[salary>15k] : Selects all the Trainee elements of the Employee element that have a salary element with a value greater than 15k.
-
/Employee/Trainee[salary>15k]/address : Selects all the address elements of the Trainee elements of the Employee element that have a salary element with a value greater than 15k.
Ask Your Question
Got a programming related question? You may want to post your question here
Programming Answers here