'OR' operator in XPath predicate?

北城余情 提交于 2019-12-30 02:36:11

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2211693/or-operator-in-xpath-predicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!