我想在这个例子中使用 for 创建一个元素列表:
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
我想得到的是:For each ingredient return the list of restaurants that use it
。我真的不明白问题出在哪里?
在这里你可以看到一个例子:http://www.xpathtester.com/xquery/0c8f9699df404020afd07ff9f9517a46
它一直在说:ERROR - Variable $res has not been declared
您的表达式被解读为(for ... let ... return $ingr), ($res)
.这意味着末尾的$res
被视为与之前的 FLWOR 表达式分开的不同表达式,因此存在未声明的变量错误。
您可以简单地使用括号来更改此不需要的分组:
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
正如 har07 正确指出的那样,需要括号才能将$res
的最终引用放入 FLWOR 表达式的范围。但是,我认为您编写的查询过于复杂,特别是量化表达式可以替换为路径表达式。这是一个更简单的变体:
for $ingr in distinct-values(//Ingredient/Name)
return ($ingr, //Restaurant[Dish/Ingredient/Name = $ingr])
问题在于在代码
中定义 $res 2您必须更改 for 循环才能让子节点位于父节点内
for $res2 in //Restaurant
let $Ingredient := distinct-values(//Ingredient/Name/data())
(:This is a list of ingredients :)
let $ingr := if (some $ingr2 in $Ingredient
satisfies (contains(lower-case($res2//Ingredient/Name), $ingr2)))
then( $res2 )
else()
)
return $ingr, $res2