Where clause to determine if element value is in a sequence (XQ)
Asked Answered
S

1

5

I am trying to pull some data from our XML-native db, IF the value of one element is in contained sequence of values. Don't think I worded that right. For example,

Given the following XML:

<root>
   <a>1</a>
<root>

Seems there should be a way to do something like (excuse syntax, treat as pseudo)

where root/a in (1,2,3,4)

From all of my searching, that doesn't seem to be possible. At best, I've gotten:

where root/a = 1 or root/1 = 2 or root/a = 3   etc

is there a better way to do this?

Sunder answered 29/4, 2016 at 2:38 Comment(0)
D
9

You can simply use = operator :

where root/a = (1,2,3,4)

= works on set values similar to contains, which is what you needed exactly. Contrast = with eq which requires atomic values for comparison.


Below is a complete example.

XML:

<root>
    <parent>
        <a>1</a>
    </parent>
    <parent>
        <a>4</a>
    </parent>
    <parent>
        <a>10</a>
    </parent>
</root>

XQuery :

for $p in /root/parent
where $p/a = (1,2,3,4)
return $p

Output :

<parent>
   <a>1</a>
</parent>
<parent>
   <a>4</a>
</parent>

demo : xpathtester

Donny answered 29/4, 2016 at 2:56 Comment(1)
+1 FYI - @Sunder you can also move the filtering from the where expression from your FLWOR into a predicate and select the parent elements with this (equivalent and shorter) XPath expression: /root/parent[a = (1,2,3,4)]Bowrah

© 2022 - 2024 — McMap. All rights reserved.