253

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>

1 Answer 1

366

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.

3
  • 5
    Without . didn't work for me (needed ./author/name) Oct 11, 2018 at 6:03
  • 1
    Is it possible to use this syntax in a function? Eg, how to implement something such as ./book[contains(author/name, "John")]? Oct 22, 2018 at 11:00
  • 3
    @OgrishMan new questions should go in New Question, 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, 2018 at 12:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.