Reputation:
I'm learning Xpath with the help of some documentation here and am stuck with a particilar query. In the Following XML Im trying to print out the <value>
of the <OwnerName>
for the books which the price is > 10 and I used the following Xpath Query to do so
strExpression = "/bookstore/book/name/value[../price>10.00]";
NodeIter = nav.Select(strExpression);
Console.WriteLine("Names of expensive books owners:");
while (NodeIter.MoveNext())
{
Console.WriteLine("Owner Name: {0}", NodeIter.Current.Value);
};
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
<book genre="autobiography">
<OwnerName>
<value>Alex dan</value>
</OwnerName>
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book genre="novel">
<OwnerName>
<value>Pam Sanderson</value>
</OwnerName>
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy">
<OwnerName>
<value>Rogger Mark</value>
</OwnerName>
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
what am I doing wrong here would really appreciate some help
Upvotes: 0
Views: 61
Reputation: 5915
You write :
/bookstore/book/name/value[../price>10.00]
Why it doesn't work :
/
at the beginning of your XPath expression (look anywhere)name
element instead of ownername
element..
(parent operator) since you want to use /price
(child of book
not ownername
)[]
(predicate) to test the book
node or the price
nodeSo to sum, to fix your XPath (following your logic) you could have 2 syntaxes :
//bookstore/book/ownername/value[../../price[.>10]]
//bookstore/book/ownername/value[../..[price>10]]
Other options (more or less consuming) :
//value[../..[price>10]]
//value[ancestor::book[1][price>10]]
//price[.>10]/preceding::value[1]
Upvotes: 0
Reputation: 77
First of all, it's necessary to change the XPath expression.
Instead of
strExpression = "/bookstore/book/name/value[../price>10.00]";
use
strExpression = "/bookstore/book[price>10.00]/OwnerName/value";
Upvotes: 1