Microsoft XML 2.5 SDK


 

Lesson 5: Using XML Namespaces

[This is preliminary documentation and subject to change.]

What is an XML namespace?

An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name. The namespace is identified by some URI (Universal Resource Identifier), either an URL (Uniform Resource Locator), or an URN (Uniform Resource Number), but it doesn't matter what, if anything, it points to. URIs are used simply because they are globally unique across the Internet.

Namespaces can be declared either explicitly or by default. With an explicit declaration, you define a shorthand, or prefix, to substitute for the full name of the namespace. You use this prefix to qualify elements belonging to that namespace. Explicit declarations are useful when a node contains elements from different namespaces. A default declaration declares a namespace to be used for all elements within its scope, and a prefix isn't used.

How do I declare an explicit namespace?

The following explicit declaration declares "bk" and "money" to be shorthand for the full names of their respective namespaces. The attribute "xmlns" is an XML keyword for a namespace declaration.

<BOOKS>
  <bk:BOOK xmlns:bk="urn:BookLovers.org:BookInfo"
           xmlns:money="urn:Finance:Money">
    <bk:TITLE>A Suitable Boy</bk:TITLE>
    <bk:PRICE money:currency="US Dollar">22.95</bk:PRICE>
  </bk:BOOK>
</BOOKS>

All elements beginning with "bk:" or "money:" are considered to be from the namespace "urn:BookLovers.org:BookInfo" or "urn:Finance:Money," respectively. Run the mouse over the XML to reveal information about the different elements.

How do I declare a default namespace?

A namepace declared without a prefix becomes the default namespace for the document. All elements and attributes in the document that don't have a prefix will then belong to the default namespace. The following example declares that the "BOOK" element and all elements and attributes within it ("TITLE", "PRICE", "currency") are from the namespace "urn:BookLovers.org:BookInfo."

<BOOK xmlns="urn:BookLovers.org:BookInfo">
  <TITLE>A Suitable Boy</TITLE>
  <PRICE currency="US Dollar">22.95</PRICE>
</BOOK>