Honza Hejzl
Honza Hejzl

Reputation: 884

How to check if an element contains more separate words in XQuery?

I have a list of items/words:

<results>
  <string>
    <part>Downs</part>
    <part>1957</part>
  </string>
  <string>
    <part>Carmines</part>
    <part>Huckfeldt</part>
    <part>1996</part>
  </string>
</results>

In a document, I need to search for paragraphs containing all parts of a particular string at once.

For me, it seems a bit tricky because I need to iterate over results items and compare all of them to every paragraph.

Something like:

for $part in $results//part
let $paragraph := $doc//p[contains(., $part)]
return
    $paragraph

This returns all paragraphs containing one or more words from every string. It is not possible to group them because they are always unique in this case.

Upvotes: 2

Views: 155

Answers (1)

Leo W&#246;rteler
Leo W&#246;rteler

Reputation: 4241

You can use quantified expressions to express exactly what you want:

for $p in $doc//p
where
  some $string in $results//string
  satisfies (
    every $part in $string/part
    satisfies contains($p, $part)
  )
return $p

Here's a shorter version:

for $p in $doc//p
where $results//string[every $part in ./part satisfies contains($p, $part)]
return $p

And finally a short but cryptic version without quantified expressions:

for $p in $doc//p
where $results//string[not(part[not(contains($p, .))])]
return $p

It returns all paragraphs for which there is a string so that none of its parts is not contained in the paragraph. ;)

Upvotes: 3

Related Questions