Query XDocument with xmlns attribute (namespace)

前端 未结 2 2055
广开言路
广开言路 2020-12-06 10:08

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

    // Working
    string xml1 = @\"

        
2条回答
  •  星月不相逢
    2020-12-06 11:05

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

提交回复
热议问题