Rob
Rob

Reputation: 16002

XQuery : how to try if a list contains a given string?

I have 2 XML files :

file1.xml

<data>doe90</data>
<data>foo</data>
<data>goo</data>
...

file2.xml

<data2>nan</data2>
<data2>goo</data2>
<data2>test</data2>
...

I stored this data in 2 vars :

let $data := //data,
$data2 := //data2

And began to do this :

for $d in $data2
return 
if() (: $d is also in $data ? :)

What should I do ? Thanks

EDIT : Of course I tried contains, but got an error :

if(contains($d,$data) = 0)

An exception occurred during query execution: XPTY0004: cannot convert 'xs:boolean(true)' to xs:integer

Upvotes: 4

Views: 26223

Answers (3)

Nicol&#225;s Maldonado
Nicol&#225;s Maldonado

Reputation: 137

This work for me:

fn:exists($data[. =($data2/text())])

Upvotes: 0

Christian Gr&#252;n
Christian Gr&#252;n

Reputation: 6229

This may help:

//data[. = //data2] ► returns elements whose string values are contained in data2 
//data = //data2    ► returns true there are any matches, false otherwise

fn:contains() won’t help here, as it was built for matching substrings:

contains('abc', 'a') ► true

Upvotes: 10

BeniBela
BeniBela

Reputation: 16917

Contains only works on strings. (although in your example it seems to convert the nodes to strings, but then fails, because it returns boolean which you cannot compare to 0. )

You can do

if (exists(index-of($data, $d)))

And

$data2[exists(index-of($data, .))] 

is probably faster than the for/if- (but still n^2)

Upvotes: 4

Related Questions