在Xquery中传递参数

Sid*_*dhu 3 xquery

让我们考虑一个示例代码

declare function local:topic(){

    let $forumUrl := "http://www.abc.com"
    for $topic in $rootNode//h:td[@class="alt1Active"]//h:a

        return
            <page>{concat($forumUrl, $topic/@href, '')}</page>

};

declare function local:thread(){

    let $forumUrl := "http://www.abc.com"
    for $thread in $rootNode//h:td[@class="alt2"]//h:a

        return
            <thread>{concat(forumUrl, $thread/@href, '')}</thread>

};
Run Code Online (Sandbox Code Playgroud)

我可以在此代码中传递任何参数,而不是重复"$ forumUrl".如果可能,请帮助我.

mic*_*ael 6

这肯定是可能的,您可以将其传入或将其声明为"全局"变量:声明变量:

declare variable $forumUrl := "http://www.abc.com";
declare variable $rootNode := doc('abc');
declare function local:topic(){
    for $topic in $rootNode//td[@class="alt1Active"]//a

        return
            <page>{concat($forumUrl, $topic/@href, '')}</page>

};

declare function local:thread(){


    for $thread in $rootNode//td[@class="alt2"]//a

        return
            <thread>{concat($forumUrl, $thread/@href, '')}</thread>

};
Run Code Online (Sandbox Code Playgroud)

或者您将URL作为参数传递:

declare variable $rootNode := doc('abc');


declare function local:topic($forumUrl){
    for $topic in $rootNode//td[@class="alt1Active"]//a

        return
            <page>{concat($forumUrl, $topic/@href, '')}</page>

};

declare function local:thread($forumUrl){


    for $thread in $rootNode//td[@class="alt2"]//a

        return
            <thread>{concat($forumUrl, $thread/@href, '')}</thread>

};
local:topic("http://www.abc.de")
Run Code Online (Sandbox Code Playgroud)

注意我从你的例子中删除了'h:'命名空间并添加了$rootNode变量.

希望这有帮助.

一般来说,XQuery函数的参数可以指定如下:

local:foo($arg1 as type) as type 其中type可以是例如:

  • xs:string 一个字符串
  • xs:string+ 至少一个字符串的序列
  • xs:string* 任意数量的字符串
  • xs:string? 一个长度为零或一个字符串的序列

函数可以包含任意数量的参数,可以省略参数的类型.

函数返回值也可以输入,在您的示例的上下文中,签名可能是:

  • declare function local:thread($forumUrl as xs:string) as element(thread)+

定义local:thread只接受一个字符串并返回一个非空的线程元素序列.

迈克尔