Namespaces are used to identify the vocabulary to which XML elements and attributes belong, and to disambiguate names from different vocabularies. This section provides a brief overview of the use of namespaces in XQuery for those who expect to be writing queries with basic use of namespaces. More detailed coverage of namespaces, including a complete explanation of the use of namespaces in XML documents, can be found in Chapter 10.
Many of the names used in a query are namespace-qualified, including those of:
Elements and attributes from an input document
Elements and attributes in the query results
Functions, variables, and types
Example 2-3 shows an input document that contains a namespace declaration, a special attribute whose name starts with xmlns
. The prod
prefix is mapped to the namespace http://datypic.com/prod. This means that any element or attribute name in the document that is prefixed with prod
is in that namespace.
Example 2-3. Input document with namespaces (prod_ns.xml)
<prod:product xmlns:prod="http://datypic.com/prod"> <prod:number>563</prod:number> <prod:name language="en">Floppy Sun Hat</prod:name> </prod:product>
Example 2-4 shows a query (and its results) that might be used to select the products from the input document.
Example 2-4. Querying with namespaces
Query declare namespace prod = "http://datypic.com/prod"; for $product in doc("prod_ns.xml")/prod:
product return $product/prod:
name Results <prod:name xmlns:prod="http://datypic.com/prod" language="en">Floppy Sun Hat</prod:name>
The namespace declaration that appears in the first line of the query maps the namespace http://datypic.com/prod to the prefix prod
. The prod
prefix is then used in the body of the query to refer to elements in the input document. The namespace (not the prefix) is considered to be a significant part of the name of an element or attribute, so the namespace URIs (if any) in the query and input document must match exactly. The prefixes themselves are technically irrelevant; they do not have to be the same in the input document and the query.
3.16.139.8