Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list using a for in XQuery 1.0

Tags:

xml

xquery

I would like to create a list of element using a for like in this example:

for $ingr in distinct-values(//Ingredient/Name)
let $res := (
  for $res2 in //Restaurant
  return if( some $ingr2 in $res2/Dish/Ingredient/Name satisfies $ingr2 eq $ingr )
    then( $res2 )
    else()
  )
return $ingr, $res

What I want to obtain is: For each ingredient return the list of restaurants that use it. I really don't understand where is the problem?

Here you can see an example: http://www.xpathtester.com/xquery/0c8f9699df404020afd07ff9f9517a46

It keep saying: ERROR - Variable $res has not been declared

like image 986
Timmy Avatar asked Jun 23 '26 19:06

Timmy


2 Answers

Your expression was read as (for ... let ... return $ingr), ($res). Which means that $res at the end is considered a different expression separate from the previous FLWOR expression, hence the undeclared variable error.

You can simply use parentheses to alter this unwanted grouping :

for $ingr in distinct-values(//Ingredient/Name)
let $res := (
  for $res2 in //Restaurant
  return if( some $ingr2 in $res2/Dish/Ingredient/Name satisfies $ingr2 eq $ingr )
    then( $res2 )
    else()
  )
return ($ingr, $res)

xpathtester demo

like image 198
har07 Avatar answered Jun 25 '26 11:06

har07


As har07 correctly points out, parentheses are needed to get the final reference of $res into the scope of the FLWOR expression. However I think the query as you wrote it is overly complex, in particular the quantified expression can be replaced by just a path expression. Here is a simpler variant:

for $ingr in distinct-values(//Ingredient/Name)
return ($ingr, //Restaurant[Dish/Ingredient/Name = $ingr])
like image 26
Gunther Avatar answered Jun 25 '26 09:06

Gunther