Names and Namespaces
Just as .NET types can have namespaces, so too can XML elements and attributes.
XML namespaces achieve two things. First, rather like namespaces
in C#, they help avoid naming collisions. This can become an issue when
you merge data from one XML file into another. Second, namespaces assign
absolute meaning to a name. The name “nil,” for
instance, could mean anything. Within the http://www.w3.org/2001/XMLSchema-instance namespace,
however, “nil” means something equivalent to null
in C# and comes with specific rules on
how it can be applied.
A namespace in XML is defined with the xmlns
attribute:
<customer
xmlns="OReilly.Nutshell.CSharp"
/>
xmlns
is a special reserved
attribute. When used in this manner, it performs two
functions:
It specifies a namespace for the element in question.
It specifies a default namespace for all descendant elements.
You can also specify a namespace with a prefix —an alias that you assign to a namespace to avoid repetition. There are two steps—defining the prefix and using the prefix. You can do both together as follows:
<nut:
customerxmlns:nut
="OReilly.Nutshell.CSharp"/>
Two distinct things are happening here. On the right, xmlns: nut="…"
defines a prefix called
nut
and makes it available to this
element and all its descendants. On the left, nut:customer
assigns the newly allocated
prefix to the customer
element.
A prefixed element does not define a default
namespace for descendants. In the following XML, firstname
has an empty namespace:
Get LINQ Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.