I am trying to get all book title with same year as Harry Potter
"/bookstore/book[year=//descendant-or-self::book[title='Harry Potter']/year]/title"
yield all books title with same year as book titled 'harry potter' correctly
"/bookstore/book[year=descendant-or-self::book[title='Harry Potter']/year]/title";
yield only books titled 'harry potter'
while, initally I did:
"/bookstore/book[year=self::book[title='Harry Potter']/year]/title";
yield only books titled 'harry potter' as well.
the XML document is from : http://www.w3schools.com/xml/xml_xpath.asp (see XML document copy-pasted below for reference)
Why the last two not yield all the results I want but only the book itself?
<?xml version="1.0" encoding="UTF-8"?>
<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>
</bookstore>
Firstly, for all practical purposes, //descendant-or-self::book
means the same as //book
, so your first expression is correct but unnecessarily verbose.
Your second expression uses book[year=descendant-or-self::book...]
. In your sample XML document, books do not have descendant books, so this is equivalent to book[year=self::book...]
, which is your third expression.
Your third expression /bookstore/book[year=self::book[title='Harry Potter']/year]/title
is very redundant. If we cut out the inner predicate it's saying
/bookstore/book[year=self::book/year]/title
which is selecting every book where the book's year is the same as the book's year - which is always true provided the book has a year.
If you leave out that tautological condition, you're left with
/bookstore/book[title='Harry Potter']/title
which selects the title of all books whose title is 'Harry Potter', which can only be zero or more repetitions of "Harry Potter".
Basically, you haven't understood the importance of context. You need to re-read that section of your favourite XPath textbook.
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