XQuery/Getting URL Parameters
< XQueryMotivation
You want to create an XQuery that takes a parameter from the calling URL.
Format
The format of a calling URL that uses the HTTP Get or POST command is:
<hostname>:<port>/<path>/xquery.xq?param1=123¶m2=456
Where param1 is the first parameter with a value of 123 and param2 is the second parameter with a value of 456.
Note that question mark is used to start the parameters and the ampersand is used to separate parameters. Remember to include "amp;" following the &.
xquery version "1.0"; let $param1:= request:get-parameter('param1', '') let $param2:= request:get-parameter('param2', "") return <results> if ($param2 = '0') then ( <message>param2 is empty</message> ) else ( <message>default message</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
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.
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
<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.
Adding a Debug Parameter
It is very common that you want to conditionally turn on part of a transform to get additional information during the debugging process.
let $debug := xs:boolean(request:get-parameter('debug', ''))