Microsoft 9GD00001 Computer Accessories User Manual


 
406 Microsoft Visual Studio 2010: A Beginner’s Guide
Namespaces
Another important part of XML that you’ll need to understand is namespaces. In Chapter 2,
you learned how namespaces in C# and VB help give a unique identity to code within a
given namespace. The purpose of namespaces in XML is similar. In the case of Listing
A-1, there is a customer element, but think about how many different programs work with
customer data. A customer in one program will not be defined the same as a customer in
another program, and you need a way to tell them apart, which is where namespaces come
in. You would define your customer data in a namespace of your choosing, and some other
developer would define a unique namespace for their customer. That way, your programs
won’t ever be confused if they try to read the wrong data. Listing A-2 shows how to use a
namespace to make a customer unique.
TIP
You might have noticed that the namespaces in Listing A-2 look like Web addresses.
However, this is just coincidence and is a common practice used to increase the chance
that the namespace is unique. In reality, the namespace is just a string, which catches
people new to namespaces off guard. For example, http://mcgraw-hill.com/vs2010bg
is a different namespace than http://mcgraw-hill.com/vs2010bg/ because the extra
forward slash on the end is a different string. So, if you made this mistake, then it’s
possible that a program won’t recognize the data as being a valid format because the
data is in a different namespace than what the program expects. Remember that a
namespace is a unique string, not a Web address.
Listing A-2 XML namespace example
<?xml version="1.0" encoding="utf-8" ?>
<customer id="7"
xmlns="http://mcgraw-hill.com/vs2010bg"
xmlns:a="http://somedomain.com/addresses">
<name>Joe</name>
<a:address>123 4th St</a:address>
</customer>
Namespaces are specified by placing an xmlns attribute on an element, either with
or without a prefix. The xmlns without a prefix specifies the default namespace for all of
the elements where the namespace resides and child elements of the element where the
namespace resides. This means that customer and name are in the http://mcgraw-hill.com/
vs2010bg namespace.
Namespaces can also have prefixes to help you target where they are applied. In
Listing A-2, there is an xmlns:a, where a is the prefix for the http://somedomain.com/