Joel Joel - 2 months ago 29
C# Question

Query XDocument with xmlns attribute (namespace)

I try to query elements from an visual studio *.csproj file. I created a short example to illustrate the problem:

// Working
string xml1 = @"<Project ToolsVersion='4.0'>
<ItemGroup Label='Usings'>
<Reference Include='System' />
<Reference Include='System.Xml' />
</ItemGroup>
</Project>";
// Not working
string xml2 = @"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup Label='Usings'>
<Reference Include='System' />
<Reference Include='System.Xml' />
</ItemGroup>
</Project>";

XDocument doc = XDocument.Parse(xml2);

foreach (XElement element in doc.Descendants("ItemGroup"))
{
Console.WriteLine(element);
}


The string xml1 works fine, xml2 doesn't return anything. The only difference between those strings is xmlns attribute in the document root.

How do i query documents containing xmlns attributes?
Why is it a problem when a xml document contains an xmlns attribute?

Answer

Why is it a problem when a xml document contains an xmlns attribute?

It's not, if you understand what it means :) Basically you've applied a default namespace URI of "http://schemas.microsoft.com/developer/msbuild/2003" to all elements. So when querying, you need to specify that namespace too. Fortunately, LINQ to XML makes that really simple:

XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument doc = XDocument.Parse(xml2);
foreach (XElement element in doc.Descendants(ns + "ItemGroup"))
{
    Console.WriteLine(element);
}