6️⃣ 🔍 XQuery Tutorial
Estimated reading: 3 minutes 33 views

🧠 XQuery Functions – Built-in and Custom Functions Explained

🧲 Introduction – Why Learn XQuery Functions?

Functions are the building blocks of any powerful query language, and XQuery is no exception. From simple string manipulation to complex numeric and node operations, XQuery functions allow you to reuse logic, format output, and extend your query capabilities. You can use both built-in functions and define custom user functions for more modular and readable code.

🎯 In this guide, you’ll learn:

  • The syntax of XQuery functions
  • Frequently used built-in functions
  • How to write and call your own functions
  • Examples for strings, numbers, sequences, and nodes

🔧 Function Syntax in XQuery

🔹 Call a Built-in Function

upper-case("xquery")

✅ Output:

XQUERY

🔹 Define a Custom Function

declare function local:add($a as xs:integer, $b as xs:integer) as xs:integer {
  $a + $b
};

local:add(10, 20)

✅ Output:

30

📘 Common Built-in XQuery Functions

🔤 String Functions

FunctionDescriptionExample
string()Converts a node to a stringstring($book/title)
upper-case()Converts text to uppercaseupper-case('xquery')
lower-case()Converts text to lowercaselower-case('XQUERY')
concat()Combines multiple stringsconcat($title, ' by ', $author)
contains()Checks for substringcontains($title, 'XML')
substring()Extracts part of a stringsubstring('XQuery', 1, 3)XQu

🔢 Numeric Functions

FunctionDescriptionExample
sum()Adds values in a sequencesum(1 to 5)15
avg()Average of valuesavg( (10, 20, 30) )
min(), max()Minimum or maximum valuemax( (1, 5, 3) )
round()Rounds to nearest whole numberround(2.6)3

📋 Sequence and Node Functions

FunctionDescriptionExample
count()Count number of items in sequencecount(//book)
distinct-values()Remove duplicates from a sequencedistinct-values(//genre)
exists()Returns true if item existsexists(//book[price > 500])
empty()Returns true if sequence is emptyempty(//book[@outofstock])

📁 Example – Format Book Summary

for $b in doc("books.xml")//book
return
  <summary>
    {concat(upper-case($b/title), ' - ₹', string($b/price))}
  </summary>

✅ Output:

<summary>LEARN XQUERY - ₹499</summary>

🧑‍💻 Custom Function Example

declare function local:format-price($price as xs:decimal) as xs:string {
  concat("₹", string($price))
};

for $b in doc("books.xml")//book
return
  <price>{local:format-price($b/price)}</price>

✅ Output:

<price>₹499</price>

✅ Best Practices for Using Functions

  • ✔️ Use local: prefix for custom functions
  • ✔️ Use built-in functions like string(), concat(), sum() frequently
  • ✔️ Validate your function types (e.g., as xs:string, as xs:integer)
  • ✔️ Keep functions pure—no side effects or stateful logic
  • ❌ Avoid writing repetitive code—refactor into reusable functions

📌 Summary – Recap & Next Steps

XQuery functions help you extend and simplify your queries. From formatting output to performing calculations and creating reusable logic, functions are the key to writing clean and maintainable XQuery code.

🔍 Key Takeaways:

  • Use built-in functions for strings, numbers, and sequences
  • Write custom functions using declare function
  • Functions make your queries modular and efficient

⚙️ Real-world relevance: Used in report formatting, content transformation, API generation, XML analytics, and reusable logic libraries.


❓ FAQs – XQuery Functions

❓ Can XQuery functions return XML nodes?
✅ Yes. You can return nodes, strings, numbers, or full sequences.

❓ What is local: in custom functions?
✅ It defines a private namespace for your custom functions.

❓ Can I pass nodes to a function?
✅ Yes. Functions can take elements, attributes, or entire node sets.

❓ Are there math and date functions?
✅ Yes. XQuery supports sum(), round(), and date/time functions like current-date().

❓ Are custom functions reusable across files?
✅ Yes, when imported via modules.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

XQuery Functions

Or Copy Link

CONTENTS
Scroll to Top