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

社会主义新天地 提交于 2019-12-11 03:31:05

问题


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


回答1:


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:


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:


This work for me:

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


来源:https://stackoverflow.com/questions/13979691/xquery-how-to-try-if-a-list-contains-a-given-string

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