4

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

3 Answers 3

10

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
2
  • How can I get data that is not in //data2 ? I tried //data[. != //data2] but got the same result.
    – Rob
    Dec 20, 2012 at 20:56
  • //data[. != //data2] will return true if there is at least one combination that matches. Try //data[not(. = //data2)] instead. Dec 20, 2012 at 21:04
3

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)

3
  • $data (the sequence) should come first Dec 20, 2012 at 20:20
  • $data2[exists(index-of($data, .))] works for data that's in $data, how to proceed to get data that is not into it ?
    – Rob
    Dec 20, 2012 at 20:49
  • Use empty instead of exists. Although Christians answer is probably better
    – BeniBela
    Dec 20, 2012 at 21:06
0

This work for me:

fn:exists($data[. =($data2/text())])
1
  • 1
    This answer actually provides nothing which is not already given in Christian Grüns answer. There is no need to use text() as the atomic value will be used anyway for the comparison. Which basically makes it $data[. = $data], so the same as Christians answer. The exists() only checks if there is at least one result. However, in general it is better (faster and easier readable) to drop the whole if comparison and use the simply query Christian proposed instead. Nevertheless, welcome to SO!
    – dirkk
    Apr 21, 2014 at 17:25

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.