O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:customer xmlns: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:

	

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required