219

What XPath can I use to select any category with a name attribute specified and any child node author with the value specified.

I've tried different variations of the path below with no success:

//quotes/category[@name='Sport' and author="James Small"]

The XML:

<?xml version="1.0" encoding="utf-8"?>
<quotes>
  <category name="Sport">
   <author>James Small<quote date="09/02/1985">Quote One</quote><quote             date="11/02/1925">Quote nine</quote></author>
  </category>
   <category name="Music">
   <author>Stephen Swann
 <quote date="04/08/1972">Quote eleven</quote></author>
  </category>
  </quotes>
Mike G
  • 4,232
  • 9
  • 40
  • 66
mjroodt
  • 3,223
  • 5
  • 22
  • 35

5 Answers5

327

Try:
//category[@name='Sport' and ./author/text()='James Small']

Cylian
  • 10,970
  • 4
  • 42
  • 55
  • 5
    For followers, the error message "Expected ], but found: &&" meant "use the and keyword instead of &&" (as this answer specifies) – rogerdpack Dec 15 '16 at 21:56
43

Use:

/category[@name='Sport' and author/text()[1]='James Small']

or use:

/category[@name='Sport' and author[starts-with(.,'James Small')]]

It is a good rule to try to avoid using the // pseudo-operator whenever possible, because its evaluation can typically be very slow.

Also:

./somename

is equivalent to:

somename

so it is recommended to use the latter.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
20

The question is not clear, but what I understand you need to select a category that has name attribute and should have child author with value specified , correct me if I am wrong.

Here is xpath:

//category[@name='Required value'][./author[contains(.,'Required value')]]
e.g
//category[@name='Sport'][./author[contains(.,'James Small')]]
vitaliis
  • 4,082
  • 5
  • 18
  • 40
akhter wahab
  • 4,045
  • 1
  • 25
  • 47
6

You can apply multiple conditions in xpath using and, or

//input[@class='_2zrpKA _1dBPDZ' and @type='text']

//input[@class='_2zrpKA _1dBPDZ' or @type='text']
Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Suman
  • 529
  • 2
  • 5
  • 20
3

Here, we can do this way as well:

//category [@name='category name']/author[contains(text(),'authorname')]

OR

//category [@name='category name']//author[contains(text(),'authorname')]

To Learn XPATH in detail please visit- selenium xpath in detail

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Avinash Pande
  • 1,510
  • 19
  • 17