Working with XDocument and Namespaces
I really like working with the new LINQ support for XML files. However, every time I work with a document that has namespaces, I stumble. For some reason, I just can’t remember all the details required to be able to use XPath expressions when you have namespaces defined in an XML file. A blog post, therefore, seems like a good idea.
Default Namespace
A common case is where an XML file has a default namespace defined at the very top. For example,
<Project ToolsVersion="3.5" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<RootNamespace>Test</RootNamespace>
<AssemblyName>Test</AssemblyName>
<OutputType>Library</OutputType>
</PropertyGroup>
...
return doc.Root.XPathSelectElement("PropertyGroup/RootNamespace").Value
XmlNamespaceManager namespaces = new XmlNamespaceManager(new NameTable());
XNamespace ns = _doc.Root.GetDefaultNamespace();
namespaces.AddNamespace("ns", ns.NamespaceName);
return doc.Root.XPathSelectElement("ns:PropertyGroup/ns:RootNamespace", namespaces).Value;