XQuery Functions
- Previous Page XQuery Selection
- Next Page XQuery Summary
XQuery 1.0、XPath 2.0 以及 XSLT 2.0 共享相同的函数库。
XQuery Functions
XQuery 含有超过 100 个内建的函数。这些函数可用于字符串值、数值、日期以及时间比较、节点和 QName 操作、序列操作、逻辑值等等。您也可在 XQuery 中定义自己的函数。
XQuery 内建函数
XQuery 函数命名空间的 URI:
http://www.w3.org/2005/02/xpath-functions
函数命名空间的默认前缀是 fn:。
提示:函数经常被通过 fn: 前缀进行调用,例如 fn:string()。不过,由于 fn: 是命名空间的默认前缀,所以函数名称不必在被调用时使用前缀。
您可以在我们的 XPath 教程中找到完整的《内建 XQuery 函数参考手册》。
函数调用实例
函数调用可与表达式一同使用。请看下面的例子:
例1:在元素中
<name>{upper-case($booktitle)}</name>
例2: 在路径表达式的谓语中
doc("books.xml")/bookstore/book[substring(title,1,5)='Harry']
例3: 在 let 语句中
let $name := (substring($booktitle,1,4))
XQuery User-Defined Functions
If the required XQuery function cannot be found, you can write your own function.
User-defined functions can be defined in queries or in separate libraries.
Syntax
declare function prefix:func_name($parameter AS data_type)
AS Return Data Type
{
(: ...function code... :)
;
Considerations for user-defined functions:
- Please use the declare function keyword
- The function name must use a prefix
- The data type of the parameters is usually consistent with the data type defined in XML Schema
- The function body must be enclosed in curly braces
An example of a user-defined function declared in a query:
declare function local:minPrice(
$price as xs:decimal?,
$discount as xs:decimal?)
AS xs:decimal?
{
let $disc := ($price * $discount) div 100
return ($price - $disc)
;
(: Below is an example of calling the above function :)
<minPrice>{local:minPrice($book/price, $book/discount)}</minPrice>
- Previous Page XQuery Selection
- Next Page XQuery Summary