230

Trying to select an element based on the value of one of it's childrens childrens

Thinking the following but not working, appreciate any help, thanks

./book[/author/name = 'John'] or

./book[/author/name text() = 'John']

Want all books where the author name = 'John'

Xml file

<list>
   <book>
      <author>
         <name>John</name>
         <number>4324234</number>
      </author>
      <title>New Book</title>
      <isbn>dsdaassda</isbn>
   </book>
   <book>...</book>
   <book>...</book>
</list>
James Walsh
  • 2,303
  • 2
  • 12
  • 4

1 Answers1

328

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

AakashM
  • 59,217
  • 16
  • 147
  • 181
  • 2
    Without `.` didn't work for me (needed `./author/name`) – MichaelChirico Oct 11 '18 at 06:03
  • Is it possible to use this syntax in a function? Eg, how to implement something such as `./book[contains(author/name, "John")]`? – Just a learner Oct 22 '18 at 11:00
  • 2
    @OgrishMan new questions should go in [New Question](https://stackoverflow.com/questions/ask), but before that I'd just try it! Generally you want single quotes `'` rather than double quotes `"` for string literals in xpath, by the way. – AakashM Oct 22 '18 at 12:25