Functions can be put in library modules, which can be imported by any query. Every module in XQuery is either a main module, which contains a query body to be evaluated, or a library module, which has a module declaration but no query body. A library module begins with a module declaration, which provides a URI that identifies the module for imports, as shown in Listing 1.20. Listing 1.20 Module Declaration for a Library Modulemodule "http://example.com/xquery/library/book" define function toc($book-or-section as element()) as element()* { for $section in $book-or-section/section return <section> { $section/@* , $section/title , toc($section) } </section> } Functions and variable definitions in library modules are namespace-qualified. Any module can import another module using a module import, which specifies the URI of the module to be imported. It may also specify the location where the module can be found: import module "http://example.com/xquery/library/book" at "file:///c:/xquery/lib/book.xq" The location is not required in an import, since some implementations can locate modules without it. Implementations are free to ignore the location if they have another way to find modules. A namespace prefix can be assigned in a module import, which is convenient since the functions in a module can only be called if a prefix has been assigned. The following query imports a module, assigns a prefix, and calls the function: import module namespace b = "http://example.com/xquery/library/book" at "file:///c:/xquery/lib/book.xq" <toc> { for $s in doc("xquery-book.xml")/book return b:toc($s) } </toc> When a module is imported, both its functions and its variables are made available to the importing module. |