XQuery/Getting URL Parameters
From Wikibooks, the open-content textbooks collection
Contents |
[edit] Motivation
You want to create an XQuery that takes a parameter from the calling URL.
[edit] Format
The format of a calling URL that uses the HTTP Get or POST command is:
<hostname>:<port>/<path>/xquery.xq?param1=abc¶m2=xyz
Where param1 is the first parameter with a value of abc and param2 is the second parameter with a value of xyz. Note that question mark is used to start the parameters and the ampersand is used to separate parameters.
xquery version "1.0";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace xs="http://www.w3.org/2001/XMLSchema";
let $param1:= request:get-parameter("param1",0)
let $param2:= request:get-parameter("param2",0)
return
<results>
<message>Got param1: {$param1} and param2: {$param2}</message>
</results>
Try this out by activating the following link. Change the parameters and see the changes reflected in the output.
getparams.xq?param1=abc¶m2=xyz
[edit] Checking Data Types
Additionally you can check the data types using the XML Schema data types and the castable as operator.
xquery version "1.0";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace xs="http://www.w3.org/2001/XMLSchema";
let $myint := request:get-parameter("myint",0)
let $myint := if ($myint castable as xs:integer)
then xs:integer($myint)
else 0
let $mydecimal := request:get-parameter("mydecimal", 0.0)
let $mydecimal := if ($mydecimal castable as xs:decimal)
then xs:decimal($mydecimal)
else 0.0
return
<results>
<message>Got myint: {$myint} and mydecimal: {$mydecimal} </message>
</results>
Try this out by activating the following link. Change the parameters and see the changes reflected in the output.
[edit] Script to echo all URL parameters
echo-parameters.xq
xquery version "1.0"; (: echo a list of all the URL parameters :) let $parameters := request:get-parameter-names() return <results> <parameters>{$parameters}</parameters> {for $parameter in $parameters return <parameter> <name>{$parameter}</name> <value>{request:get-parameter($parameter, '')}</value> </parameter> } </results>
Here are the results of sending the parameters "a=1&b=2" to this XQuery:
echo-parameters.xq?a=1&b=2 [1]
<results> <parameters>b a</parameters> <parameter> <name>b</name> <value>2</value> </parameter> <parameter> <name>a</name> <value>1</value> </parameter> </results>
Change parameters in the URL and see the changes reflected in the output.