使用XQuery 1.0中的for创建列表

时间:2016-01-27 10:45:57

标签: xml xquery

我想在这个例子中使用for like创建一个元素列表:

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

3 个答案:

答案 0 :(得分:4)

您的表达式被视为(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

答案 1 :(得分:2)

正如har07正确指出的那样,需要使用括号将$res的最终引用放入FLWOR表达式的范围内。但是我认为你编写的查询过于复杂,特别是量化表达式只能用路径表达式代替。这是一个更简单的变体:

for $ingr in distinct-values(//Ingredient/Name)
return ($ingr, //Restaurant[Dish/Ingredient/Name = $ingr])

答案 2 :(得分:0)

问题在于在代码中定义$ res2 你必须改变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
相关问题