Reputation: 245
Looking at the following XML-Example:
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<price>39.95</price>
<title lang="eng">Learning XML</title>
</book>
</bookstore>
Using XPath i wan't to select all books with first child being a title element and second child being a price element. This would return the first book in the example.
I tried the following expression:
book[title[1] and price[2]]
But this expression doesn't match, because it's selecting all books with at least one title element and with at least two price elements. How can i change this expression to select all books with first child being a title element and second child being a price element?
Upvotes: 3
Views: 1264
Reputation: 474171
You can do it by getting the title
child and check if there is the following price
sibling:
//book[title/following-sibling::price]
Demo (using xmllint
):
$ xmllint input.xml --xpath '//book[title/following-sibling::price]'
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
Another approach would be to check the name()
s of the first and second children of book
node:
//book[name(*[1]) = "title" and name(*[2]) = "price"]
Upvotes: 1