XQuery 在谓词中使用函数

XQuery using function in predicates

我正在学习XQuery,对last()等函数很好奇。据我了解 from the documentation,我可以这样:

doc('http://www.functx.com/input/catalog.xml')/catalog/product[last()]

据我了解,这传递了产品元素的顺序:

doc('http://www.functx.com/input/catalog.xml')/catalog/product

... 到 last(),然后 returns 最后一个成员。但是,last() 不应该接受任何参数,那么数据结构是如何传递给函数的呢?

谢谢!

引自 Walmsley, p. 49:

The position and last functions are... useful when writing predicates based on position... [Omitted here is a discussion of position.] The last function returns the number of nodes in the current sequence. It takes no arguments and returns an integer representing the number of items. The last function is useful for testing whether an item is the last one in the sequence. For example, catalog/product[last()] returns the last product child of catalog.

所以,基本上,这些函数在它们的上下文序列上运行,而不是在传递给它们的 parameters/arguments 上运行。 position returns 上下文项在上下文序列中的位置,而 last returns 当前序列中的节点数。

XQuery 是 XPath 的扩展,但这个问题的答案完全与 XPath 相关。

XPath 表达式具有动态上下文;这是 XPath 规范中的详细信息:http://www.w3.org/TR/xpath-30/#id-xp-evaluation-context-components。上下文项可以引用为 .:

fn:doc('http://www.functx.com/input/catalog.xml')/catalog/product[. eq "my product name"]

谓词 [. eq "my product name"] 为每个产品元素重新评估,. 是对上下文项的引用,即特定于该评估的元素。

几个 XPath 函数只接受上下文,而其他函数默认为上下文,带有可选参数。

下面是仅接受 XPath 3 上下文的函数的完整列表:http://www.w3.org/TR/xpath-functions-30/#context

一些例子:

  • fn:last() 采用零个参数和 returns 上下文项的大小

如果有 10 个 <product/> 个元素,则以下表达式是等价的:

fn:doc('http://www.functx.com/input/catalog.xml')/catalog/product[fn:last()]

fn:doc('http://www.functx.com/input/catalog.xml')/catalog/product[10]
  • fn:position() 接受零参数和 returns 上下文位置

fn:doc('http://www.functx.com/input/catalog.xml')/catalog/product[fn:position() > 3]


有许多函数采用零或 1 个参数,其中零参数形式访问上下文。我看到其中的 15 个,正在搜索此短语的规范:"The zero-argument form of this function is ·deterministic·, ·context-dependent·, and ·focus-dependent·."

一个例子:

  • fn:string() 采用零或 1 个参数,returns 参数或上下文项作为字符串

fn:doc('http://www.functx.com/input/catalog.xml')/catalog/product/fn:string()

returns 每个 <product/> 元素的字符串值。相当于

fn:doc('http://www.functx.com/input/catalog.xml')/catalog/product/fn:string(.)

其中上下文项作为参数显式传递。 fn:string()也可以用于类型转换:fn:string(1)returns"1".