XQuery Functions


XQuery includes an array of built-in functions. These functions are used for all the way from working with string values to numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more. In addition to the built-in functions, you can also define your own custom functions in XQuery. The following sections explore the XQuery built-in functions.

XQuery Built-In Functions

The XQuery namespace that contains all the XPath functions is identified by w3.org/2005/02/ xpath-functions. When you use these built-in functions, you can use the prefix fn:. For example, you can invoke the string() function using the default prefix fn:string(). However you can invoke the same function just as string() leaving out the fn: prefix since fn: is the default prefix of the name-space. For example, here are some examples of functions usage inside an XQuery.

  • q You can use functions to format the contents of an XML element Inside an XML element:

          <name>{upper-case($Name)}</name> 
  • q You can also use functions inside the predicate of a XPath query for performing operations such as string comparisons, and so on to introduce new conditions:

          doc("Products.xml")/Products/Product[substring(Name,1,5)='Sport'] 

  • q You can also use functions in a let clause before assigning the values to a XQuery variable as follows:

          let $name := (substring($Name,1,5)) 

As you can see from the previous examples, XQuery built-in functions are very handy and go a long way in effectively applying the power of XQuery to solve real world problems. Now that you have had an idea of the role of the functions supplied with XQuery, let us explore some of the useful built-in functions.

doc() Function

The doc (uri) function returns the root node of the referenced document. The URI reference format is implementation dependent. For example, doc(“Products.xml”) returns the root node of the Products.xml document.

Aggregate Functions

XQuery provides count, avg, max, min and sum aggregate functions, which do the following:

  • q count returns the number of items in the sequence.

  • q avg returns the average (mean) of a sequence of numbers.

  • q sum returns the sum of a sequence of numbers.

  • q max returns the number with maximum value from a sequence.

  • q min returns the number with minimum value from a sequence.

For example, the following query calculates the number of products contained in the Products.xml file:

      let $products := doc("Products.xml")/Products//Product      return        <itemCount> {count($products) } </itemCount> 

In the preceding XQuery, the $products variable represents all the product elements in the Products.xml file. The count($products) function returns the count of products in that sequence. The return clause constructs an element that looks like this:

      <itemCount> 4 </itemCount> 

String Functions

XQuery provides the following string functions: concat, starts-with, ends-with, contains, substring, string-length, normalize, upper-case, and lower-case.

The function starts-with (str1, str2) returns true if the beginning of str1 matches the characters in str2. The function ends-with (str1, str2) returns true if the ending characters in str1 match the characters in str2. The function contains(str1, str2) returns true if str1 contains str2.

The following query uses the contains() function to find products in the Products.xml whose category is of type "Socks":

      for  $product in doc("Products.xml")/Products/Product      where contains($product/@Category, "Socks")        return $product/Name 

This results in the following output:

      <Name>Mountain Bike Socks, M</Name>      <Name>Mountain Bike Socks, L</Name> 

XQuery User-Defined Functions

The nice thing about XQuery is that if you can't find the right XQuery function out of the box, you are free to write your own. These user-defined functions can be defined in the query or in a separate library. The syntax for user-defined functions is as follows:

      declare function prefix:function_name($parameter AS datatype)        AS returnDatatype      {        (: ...function code here... :)      }; 

The following are the key characteristics of a user-defined function that you need to be aware of while writing user-defined functions:

  • q The functions use the “declare function” keyword.

  • q The name of the function must be prefixed.

  • q The data types of the parameters are mostly the same as the data types defined in XML schema.

  • q The body of the function must be surrounded by curly braces.

Here is an example of a user-defined function:

      declare function local:minPrice(        $price as xs:decimal,        $discount as xs:decimal)        as xs:decimal      {        let $disc := ($price * $discount) div 100        return ($price - $disc)      }; 

And here is an example of how to call the minPrice function:

      <minPrice>        {local:minPrice($book/price, $book/discount)}      </minPrice> 

The following is another example that illustrates the declaration and use of a local function. In this case, the function accepts a sequence of employee elements, summarizes them by department, and returns a sequence of dept elements:

      declare function local:summary($emps as element(employee)*)        as element(dept)*      {        for $d in fn:distinct-values($emps/deptno)        let $e := $emps[deptno = $d]        return          <dept>            <deptno>{$d}</deptno>            <headcount> {fn:count($e)} </headcount>            <payroll> {fn:sum($e/salary)} </payroll>         </dept>      }; 

To prepare a summary of the employees located in Phoenix, invoke the above function as follows:

      local:summary(fn:doc("Employees.xml")//employee[location = "Phoenix"]) 




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net