Partilhar via


Namespaces Overview (LINQ to XML)

This topic introduces namespaces, the XName class, and the XNamespace class.

XML Names

XML names are often a source of complexity in XML programming. An XML name consists of an XML namespace (also called an XML namespace URI) and a local name. An XML namespace is similar to a namespace in a .NET Framework-based program. It enables you to uniquely qualify the names of elements and attributes. This helps avoid name conflicts between various parts of an XML document. When you have declared an XML namespace, you can select a local name that only has to be unique within that namespace.

Another aspect of XML names is XML namespace prefixes. XML prefixes cause most of the complexity of XML names. These prefixes enable you to create a shortcut for an XML namespace, which makes the XML document more concise and understandable. However, XML prefixes depend on their context to have meaning, which adds complexity. For example, the XML prefix aw could be associated with one XML namespace in one part of an XML tree, and with a different XML namespace in a different part of the XML tree.

One of the advantages of using LINQ to XML with C# is that you do not have to use XML prefixes. When LINQ to XML loads or parses an XML document, each XML prefix is resolved to its corresponding XML namespace. After that, when you work with a document that uses namespaces, you almost always access the namespaces through the namespace URI, and not through the namespace prefix. When developers work with XML names in LINQ to XML they always work with a fully-qualified XML name (that is, an XML namespace and a local name). However, when necessary, LINQ to XML allows you to work with and control namespace prefixes.

When using LINQ to XML with Visual Basic and XML literals, you must use namespace prefixes when working with documents in namespaces.

In LINQ to XML, the class that represents XML names is XName. XML names appear frequently throughout the LINQ to XML API, and wherever an XML name is required, you will find an XName parameter. However, you rarely work directly with an XName. XName contains an implicit conversion from string.

For more information, see XNamespace and XName.

See Also

Other Resources

Working with XML Namespaces