Here's some xml:
<books>
<book>
<author>Tom</author>
<genres>
<genre>Science</genre>
<genre>Romance</genre>
</genres>
</book>
<book>
<author>Mike</author>
<genres>
<genre>Politics</genre>
<genre>Romance</genre>
</genres>
</book>
</books>
How can I define an xpath such that it pulls all Romance books? Or maybe all Romance and Politics books?
You can go with //book[./genres/genre = 'Romance']
and //book[./genres/genre = 'Romance' and ./genres/genre = 'Politics']
, respectively
All books in Romance genre:
//book[genres/genre = 'Romance']
All books in Romance and Politics genre:
//book[genres/genre = 'Romance' and genres/genre = 'Politics']
All books in Romance that are also in Politics genre (same as and
above):
//book[genres/genre = 'Romance'][genres/genre = 'Politics']
All books in Romance or Politics genre:
//book[genres/genre = 'Romance' or genres/genre = 'Politics']
All books in Romance or Politics genre (XPath 2.0 only):
//book[genres/genre = ('Romance', 'Politics')]
Notes:
//book
finds all book
elements anywhere beneath the root
element; /books/book
finds all book
children of the books
root
element. For the given XML, they select the same elements./author
to any of the above XPaths to select the
author
elements of the books of the specified criteria.First, establish that a basic XPath works: //book
should return two elements.
If it does not:
Then, incrementally add XPath steps from there:
//book[genres]
should select book
elements with any genres
child element.
//book[genres/genre]
should select book
elements with any
genres
child element, only if it in turn has a genre
child
element.
//book[genres/genre = 'Romance']
should select all books in
Romance genre, as requested. Note that 'Romance'
must be quoted;
otherwise, the expression would be testing against the string value
of a Romance
child element of book
and will certainly fail.
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