Query XDocument with xmlns attribute (namespace)

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);
}

Leave a Comment