XQuery Declare Namespace Prolog Statement Guide

The declare namespace prolog statement in an XQuery script assigns a namespace prefix to a specific Uniform Resource Identifier (URI), enabling the query processor to accurately target and retrieve elements and attributes in XML documents that use namespaces. By bridging the prefixes used within the query to the URIs defined in the underlying XML dataset, this declaration ensures that path expressions resolve correctly and avoid naming collisions across different XML vocabularies.

Purpose of the declare namespace Statement

XML namespaces prevent naming conflicts by grouping elements and attributes into unique URI domains. When XML data uses namespaces, standard path expressions without namespace qualifications will fail to match target nodes. The declare namespace statement explicitly defines this relationship in the XQuery prolog before any queries are executed.

Syntax and Basic Usage

The syntax for declaring a namespace in the XQuery prolog is straightforward:

declare namespace prefix = "namespace_URI";

Practical Example

Consider the following XML snippet representing a product catalog:

<store:inventory xmlns:store="http://example.org/store"
                 xmlns:media="http://example.org/media">
    <store:item>
        <media:title>Database Systems</media:title>
        <store:price>49.99</store:price>
    </store:item>
</store:inventory>

To extract the book title using XQuery, you declare the corresponding namespace in the prolog:

declare namespace s = "http://example.org/store";
declare namespace m = "http://example.org/media";

for $item in /s:inventory/s:item
return $item/m:title/text()

In this example, the prefix chosen in the XQuery (s and m) does not need to match the prefixes used in the source XML file (store and media). The XQuery engine resolves nodes based strictly on the matching URI (http://example.org/store and http://example.org/media), providing flexibility when querying across documents with inconsistent prefix naming.

Key Benefits