Welcome to the XQuery Functions tutorial! In this lesson, we'll delve into the world of XQuery functions, understanding their importance, and learning how to use them effectively. Let's get started! 📝
XQuery functions are reusable pieces of code that perform specific tasks on XML documents. They can be defined locally within a query or globally in a module. XQuery functions are essential for handling complex XML data efficiently and effectively.
A basic function declaration looks like this:
declare function local:functionName(parameters) {
// Function body
}Let's create a simple function that calculates the sum of two numbers:
declare function local:add($num1 as xs:integer, $num2 as xs:integer) {
$num1 + $num2
}XQuery comes with a rich library of built-in functions that can help you perform various operations on XML data. Let's explore some of them:
doc() function 💡The doc() function is used to load an XML document.
Example:
let $doc = doc("<root><element>Hello</element></root>")
return $doc/elementfn:count() function 💡The count() function returns the number of elements in a sequence.
Example:
let $doc = doc("<root><element1>A</element1><element2>B</element2><element3>C</element3></root>")
return count($doc/element*)Now that we've covered the basics, let's dive into some practical use cases.
Suppose we have an XML document containing employee data:
<employees>
<employee id="1">
<name>John</name>
<position>Manager</position>
<salary>50000</salary>
</employee>
<employee id="2">
<name>Mike</name>
<position>Developer</position>
<salary>40000</salary>
</employee>
<employee id="3">
<name>Lisa</name>
<position>Designer</position>
<salary>35000</salary>
</employee>
</employees>We can create a function to find the employee with the highest salary:
declare function local:highestSalaryEmployee($employees as element()) {
$maxSalary := 0
$maxSalaryEmployee := ()
for $employee in $employees/employee
let $salary := $employee/salary
if ($salary > $maxSalary) then
return $employee
return $maxSalaryEmployee
}Suppose we have an XML document with a list of products:
<products>
<product id="1">
<name>Product A</name>
<price>100</price>
</product>
<product id="2">
<name>Product B</name>
<price>200</price>
</product>
<product id="3">
<name>Product C</name>
<price>300</price>
</product>
</products>We can create a function to convert the product list into a comma-separated list of product names and prices:
declare function local:productListToCSV($products as element()) {
$csv := ""
for $product in $products/product
let $name := $product/name
let $price := $product/price
let $formattedPrice := concat($price, ",\"", $name, "\"")
if (not($csv =="")) then
let $formattedCSV := concat($csv, ",", $formattedPrice)
return $formattedCSV
return $formattedPrice
}What does the `doc()` function do in XQuery?
Happy learning! ✅