user13719546
user13719546

Reputation:

Querying elements in Xpath using C#

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

Answers (2)

E.Wiest
E.Wiest

Reputation: 5915

You write :

/bookstore/book/name/value[../price>10.00]

Why it doesn't work :

  • Missing / at the beginning of your XPath expression (look anywhere)
  • You're calling name element instead of ownername element
  • Missing one .. (parent operator) since you want to use /price (child of book not ownername)
  • Missing [] (predicate) to test the book node or the price node

So 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

Daniel Judele
Daniel Judele

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

Related Questions