Xquery Functions in XML
XQuery Functions in XML
What are XQuery Functions?
XQuery provides built-in functions to manipulate XML data, strings, numbers, dates, and more.
Functions help perform operations like string manipulation, node handling, mathematical calculations, and sequence processing.
You can also define your own user-defined functions.
Commonly Used Built-in XQuery Functions
| Function | Purpose | Example | Result |
|---|---|---|---|
fn:string() | Converts value to string | fn:string(123) | "123" |
fn:concat() | Concatenates strings | fn:concat("Hello", " ", "World") | "Hello World" |
fn:contains() | Checks if a string contains a substring | fn:contains("Hello World", "World") | true |
fn:substring() | Returns a substring | fn:substring("Hello", 2, 3) | "ell" |
fn:count() | Counts nodes or items in a sequence | fn:count(/library/book) | 3 |
fn:starts-with() | Checks if a string starts with a substring | fn:starts-with("Hello", "He") | true |
fn:upper-case() | Converts string to uppercase | fn:upper-case("hello") | "HELLO" |
fn:lower-case() | Converts string to lowercase | fn:lower-case("HELLO") | "hello" |
fn:not() | Returns logical NOT | fn:not(true()) | false |
fn:substring-before() | Returns substring before a given string | fn:substring-before("2025-06-04", "-") | "2025" |
fn:substring-after() | Returns substring after a given string | fn:substring-after("2025-06-04", "-") | "06-04" |
Example: Using Functions in XQuery
Given this XML:
<library> <book category="fiction"> <title>The Hobbit</title> </book> <book category="history"> <title>Sapiens</title> </book></library>XQuery:
for $b in /library/bookwhere fn:contains($b/@category, "fiction")return fn:upper-case($b/title/text())Result:
THE HOBBITDefining Your Own Function
declare function local:greet($name as xs:string) as xs:string { concat("Hello, ", $name, "!")};local:greet("Vikash")Output:
Hello, Vikash!Summary
Use built-in functions for string, number, boolean, and node operations.
Functions help make XQuery expressions more powerful and concise.
You can declare your own functions for reusable code blocks.
Want examples for specific functions or help writing your own functions?