XML/XQuery/function

Материал из Web эксперт
Перейти к: навигация, поиск

Define your own function

Simple function
File: Query.xquery
declare namespace math = "http://wbex.ru";
declare function math:add($op1 as xs:integer, $op2 as xs:integer) as xs:integer
{
  $op1 + $op2  
};
declare variable $op1 as xs:integer := 1;
declare variable $op2 as xs:integer := 2;
<add>
  <op1>{$op1}</op1>
  <op2>{$op2}</op2>
  <result>{math:add($op1, $op2)}</result>
</add>

Output:

<?xml version="1.0" encoding="UTF-8"?>
<add>
   <op1>1</op1>
   <op2>2</op2>
   <result>3</result>
</add>



Recursive function

File: Query.xquery

declare namespace math = "http://wbex.ru";
declare variable $n as xs:integer external;
declare function math:factorial($integer as xs:integer) as xs:double
{
  if ($integer gt 1) then $integer * math:factorial($integer - 1) else 1
};
concat(2, "! = ", math:factorial(2))

Output:
<?xml version="1.0" encoding="UTF-8"?>2! = 2



Useful-function: between-inclusive

File: Data.xml

<order>
  <car model="A">
    <id>1</id>
    <name language="en">name 1</name>
    <colorChoices>navy black</colorChoices>
  </car>
  <car model="B">
    <id>2</id>
    <name language="en">name 2</name>
  </car>
  <car model="B">
    <id>8</id>
    <name language="en">name 3</name>
  </car>
</order>
File: Query.xquery
declare namespace functx = "http://www.wbex.ru";
declare function functx:between-inclusive
 ($value as xs:anyAtomicType, $minValue as xs:anyAtomicType,$maxValue as xs:anyAtomicType) as xs:boolean  {
   $value >= $minValue and $value <= $maxValue
 };

(: Example call :)
let $prod := doc("Data.xml")//car[1]
return functx:between-inclusive ($prod/id, 1, 5)