In XPath, what does it mean when you write a query that includes two consecutive values enclosed in []
, like a Java array [][]
For example:
//bookstore/book[3][1]
When I do this, I get the 3rd book as the result (the same if I would have just said //bookstore/book[3]
I've been trying to play with this and determine what exactly is happening, for example, I tried //bookstore/book[3][2]
and //bookstore/book[3][0]
but got no results. It seems to only work if the second value is 1
but I have no clue why.
Here is the XML I'm playing with:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J. K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book category="OPENSOURCE">
<title lang="en">Open Source</title>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
The predicates operate in a context. When you use //bookstore/book[3]
(which is equivalent to //bookstore/book[position()=3]
) you are restricting the node-set to the matching node in the third position. In that context if you add an extra predicate like [1]
you are simply selecting the one and only node available.
This is useful if your first predicate results in a node-set which you wish to add more restrictions with another predicate. For example, if your first predicate had restricted the nodes by selecting the year
//bookstore/book[year=2005]
you would have two nodes, and you could select the first one of those 2 with a second predicate, selecting the position:
//bookstore/book[year=2005][1]
You can add any number of [1]s after you have only one node, since it the result will always a node-set containing one node, and you are selecting the one in the first position:
//bookstore/book[3][1][1][1][1][1][1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With