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

20,952

Solution 1

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.

Solution 2

Does this work?

//Book[@size='2']//Title[text() = "xyz"]/..
Share:
20,952
anamik
Author by

anamik

Updated on July 09, 2022

Comments

  • anamik
    anamik almost 2 years

    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