XPath Predicate
XPath Predicate
XPath Predicate refers to the XPath expression written in square brackets. It refers to restrict the selected nodes in a node set for some condition.
XPath Predicates are used to find a specific node or a node that contains a specific value.
note
XPath Predicates are always embedded in square brackets.
Example
Consider the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">A Great Book</title>
<author>Tom Nolan</author>
<price>19.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<author>Tutorial Reference</author>
<price>29.99</price>
</book>
</bookstore>
In the following table there are some path expressions with predicates and the result of the expressions:
Path Expression | Result |
---|---|
/bookstore/book[1] | Selects the first book element that is the child of the bookstore element. |
/bookstore/book[last()] | Selects the last book element that is the child of the bookstore element |
/bookstore/book[last()-1] | Selects the last but one book element that is the child of the bookstore element |
/bookstore/book[position()<3] | Selects the first two book elements that are children of the bookstore element |
//title[@lang] | Selects all the title elements that have an attribute named lang |
//title[@lang='en'] | Selects all the title elements that have a "lang" attribute with a value of "en" |
/bookstore/book[price>15.00] | Selects all the book elements of the bookstore element that have a price element with a value greater than 15.00 |
/bookstore/book[price>15.00]/title | Selects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 15.00 |
note
In IE 5,6,7,8,9 first node is[0], but according to W3C, it is [1].
To solve this problem in IE, set the SelectionLanguage
to XPath.
In JavaScript, you can do in this way: xml.setProperty("SelectionLanguage","XPath");