165
votes

How can I do with XPath:

//bookstore/book/title or //bookstore/city/zipcode/title

Just //title won't work because I also have //bookstore/magazine/title

p.s. I saw a lot of or examples but mainly with attributes or single node structure.

3
OR is inclusive of both sides. What you're looking for is the XOR operator. You're conflating the English usage of the word OR with logical operators.Zoran Pavlovic
In this case it makes no difference whether you use or or xor as it's not possible to match both sides.Dan Hulme

3 Answers

243
votes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

65
votes

If you want to select only one of two nodes with union operator, you can use this solution: (//bookstore/book/title | //bookstore/city/zipcode/title)[1]

10
votes

It the element has two xpath. Then you can write two xpaths like below:

xpath1 | xpath2

Eg:

//input[@name="username"] | //input[@id="wm_login-username"]