Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'OR' operator in XPath predicate?

What is the XPath expression to select <link> elements with type="application/rss+xml" OR type="application/atom+xml" (RSS and Atom feeds)

  • link[@rel='alternate'][@type='application/rss+xml'] selects RSS feeds
  • link[@rel='alternate'][@type='application/atom+xml'] selects Atom feeds

But what is the single XPath expression for selecting them both?

Thank you.

like image 344
abernier Avatar asked Feb 06 '10 02:02

abernier


People also ask

How do you write or in XPath?

if you are looking OR (|) operator in xpath, you can try like this "(.//span[@class='g-title'])[2]|.//span[@class='g-title']" .

What is an XPath predicate?

Advertisements. Predicate refers to the XPath expression written in square brackets. It refers to restrict the selected nodes in a node set for some condition.


2 Answers

use:

link[@rel='alternate'][@type='application/rss+xml' or @type='application/atom+xml']  

see http://www.w3.org/TR/xpath/#NT-OrExpr

You could also use union to accomplish this

link[@rel='alternate'][@type='application/rss+xml']|link[@rel='alternate'][@type='application/atom+xml'] 

but or will do.

like image 126
Jonathan Fingland Avatar answered Nov 13 '22 08:11

Jonathan Fingland


if you want to get fancy and use XPath 2.0, it is more elegant (but potentially confusing, depending who might be reading the code) to write it like this:

link[@rel='alternate'][@type = ('application/rss+xml', 'application/atom+xml')]  

the reason for this is that XPath 2.0 redefines '=' to apply to sequences, which means that the above comparison returns true if there is one match when comparing items from the left-hand sequence with comparing items from the right-hand sequence. this can be very useful if the list of things you want to compare with is dynamic.

like image 36
dret Avatar answered Nov 13 '22 09:11

dret