xml
  1. xml-namespaces

XML Namespaces

XML namespaces allow elements and attributes to be defined and named without the possibility of naming conflicts with elements and attributes in other XML namespaces.

Syntax

The syntax of an XML namespace declaration is as follows:

xmlns:prefix="namespaceURI"
  • xmlns stands for "XML namespace"
  • prefix is a short string used to identify the namespace within the XML document
  • namespaceURI is a unique identifier used to distinguish the namespace from others

Example

Consider the following example where we define two namespaces xhtml and myNS:

<html xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:myNS="http://www.example.com/myNS">
  <head>
    <xhtml:title>My Web Page</xhtml:title>
    <myNS:author>John Doe</myNS:author>
  </head>
  <body>
    <xhtml:p>This is a paragraph.</xhtml:p>
    <myNS:note><xhtml:em>Note:</xhtml:em> This is some important information.</myNS:note>
  </body>
</html>

Explanation

In the above example, we have declared two namespaces:

  • xhtml with the URI http://www.w3.org/1999/xhtml
  • myNS with the URI http://www.example.com/myNS

We use the xmlns attribute on the html tag to declare the two namespaces.

The xhtml namespace is used to define the title and p elements, while the myNS namespace is used to define the author and note elements.

Use

XML namespaces are commonly used in conjunction with other XML technologies such as XPath, XQuery, and XSLT to manipulate and transform XML documents.

Important Points

  • XML namespace URIs must be unique and fully qualified URIs.
  • Namespace prefixes do not have any effect on the parsing or processing of an XML document, they are simply used as a convenient shorthand for identifying the namespaces within the document.
  • It is common practice to use prefixes that are commonly associated with a particular namespace, for example, the xhtml prefix for the http://www.w3.org/1999/xhtml namespace.

Summary

In summary, XML namespaces are used to define unique identifiers for elements and attributes within an XML document, preventing naming conflicts with elements and attributes in other namespaces. We declare namespaces using the xmlns attribute and a prefix, and use these prefixes to identify which namespace an element or attribute belongs to.

Published on: