O'Reilly logo

XQuery from the Experts: A Guide to the W3C XML Query Language by Philip Wadler, Jim Tivy, Jérôme Siméon, Michael Rys, Jonathan Robie, Michael Kay, Mary Fernández, Denise Draper, Don Chamberlin, Howard Katz - Editor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

User-Defined Functions

When a query becomes large and complex, it is often much easier to understand if it is divided into functions, and these functions can be reused in other parts of the query. For instance, we have seen a query that inverts a hierarchy to create a list of books by each author in a bibliography. It contained the following code:

for $b in doc("books.xml")/bib/book
where some $ba in $b/author satisfies
        ($ba/last=$l and $ba/first=$f)
order by $b/title
return $b/title

This code returns the titles of books written by a given author whose first name is bound to $f and whose last name is bound to $l. But you have to read all of the code in the query to understand that. Placing it in a named function makes its purpose clearer:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required