I'm trying to select the title value where the attribute value is greater than 1:
path="//book/price[@value >1]
I'm not exactly sure how to select only the titles where the attribute value for the element price is greater than one. I'm an XML beginner and I'm doing a few exercises from a tutorial.
My priorities are
XML:
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price value="1">49.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price value="2">29.95</price>
</book>
<book>
<title lang="en">super xml</title>
<price value="3">39.95</price>
</book>
</bookstore>
Update
The first query was perfect could you show me how to obtain it from a nested element?
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<possibleprice>
<price value="1">49.99</price>
</possibleprice>
</book>
<book>
<title lang="en">Learning XML</title>
<possibleprice>
<price value="2">29.95</price>
</possibleprice>
</book>
<book>
<title lang="en">super xml</title>
<possibleprice>
<price value="3">39.95</price>
</possibleprice>
</book>
</bookstore>
For example:
For the first version of the OP:
Input:
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price value="1">49.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price value="2">29.95</price>
</book>
<book>
<title lang="en">super xml</title>
<price value="3">39.95</price>
</book>
</bookstore>
XPath:
//book/price[@value > 1]/preceding-sibling::title
Result:
<title lang="en">Learning XML</title>
<title lang="en">super xml</title>
For the updated second XML version of OP, as different example:
XPath:
//book/possibleprice/price[@value > 1]/ancestor::book/title
Same result as above.
To answer the question in the comment if it would be necessary to use preceding-sibling twice for the 2nd version: no. preceding-sibling
targets the preceding-sibling
of the current node. The current node in this case is price and has no siblings, but the parent
possibleprice . To get the same result in a different way as given above, it would be possible to get the parent
of price and then the preceding-sibling
of possibleprice :
//book/possibleprice/price[@value > 1]/parent::possibleprice/preceding-sibling::title
which results in the same.
As mentioned that OP is a beginner in XML, maybe the following can be useful to illustrate XPath axes: http://www.xmlplease.com/axis
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.