10

Is there is an operator in XPath 1.0 that acts as "in" operator in SQL?

select * from tbl_students where id in (1,2,3)
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Heba El-Fadly
  • 281
  • 1
  • 5
  • 17

3 Answers3

17

The = operator of XPath 1.0 works that way, though XPath 1.0 doesn't provide syntax for writing sequences. So if you have an XML document of the form

<doc>
  <value>1</value>
  <value>2</value>
  <value>3</value>
</doc>

then an expression like //doc[value = 2] will return that doc element.

In XPath 2.0, the syntax (1, 2, 3) will create a sequence of three integers, and you can write conditions like $i = (1, 2, 3). But literal sequences are not a feature of XPath 1.0 -- the only way to get multiple values on one side of an XPath expression is to use a path expression that matches multiple nodes.

C. M. Sperberg-McQueen
  • 24,596
  • 5
  • 38
  • 65
7

I had the same problem, the above answer is right. To make it more clear, in Xpath this will look something like:

//*:document[*:documentType=("magazine","newspaper")]

wich would be the equivalant of:

select * from documents where documenttype in ('newsletter','magazine')
ErikL
  • 2,031
  • 6
  • 34
  • 57
  • Just to complement another example: You can use `.=("abc", "bcd")` for check if current node value is one of the specified strings. – jediz Jun 19 '18 at 13:59
  • 2
    It should be noted that this syntax relies on Xpath 2.0, the question is tagged as xpath 1.0; this answer is not helpful to me personally. I ended up simply making repeated templates using a regular expression. – Joeppie Dec 07 '18 at 16:46
1

To find out if the 'id' you search is in the sequence of (1, 2, 3, 4) index-of() might be a choice. Pay attention it returns list of indexes.

For a document part like

<student id='1'/>
<student id='101'/>
<student id='1001'/>

Select will something like

//*[not(empty(index-of((1, 2, 3, 4), @id)))]
vzH
  • 19
  • 1
  • I upvoted this, but this answer is Xpath 1.0, unfortunately, I can no longer downvote this, as would be appropriate. Sorry. – Joeppie Dec 07 '18 at 16:45