Search code examples
xmlxpathselectsinglenode

xpath query for finding an element with a condition which matches the attribute and child node value


I have 2 elements with same attribute but with different child node values. Can I query to find a specific element which matches the attribute and also the child node value. To be specific, this is the sample xml i am using to query(each element in original xml has more than 10 childe nodes).

 <Book size="2">
  <Title>abc</Title>
  <Price>10</Price>
 </Book>
 <Book size="2">
  <Title>xyz</Title>
  <Price>20</Price>
 </Book>
 <Book size="4">
  <Title>Harry</Title>
  <Price>10</Price>
 </Book>

So, now I want to find the Book element which has the @size = "2" and Title = xyz.

Is this possible by using SelectSingleNode method? If not how to query this?

Thanks


Solution

  • This:

    //Book[@size='2'][Title='xyz']
    

    Or this:

    //Book[@size='2' and Title='xyz']
    

    Note that the use of // is discouraged when your schema is known.