Parse csproj via c# - cannot parse ItemGroup

好久不见. 提交于 2019-12-07 17:20:43

问题


I try to get all dll names from csproj file, but cannot get anything! So,i try to get al elements from ItemGroup tag with liq query:

 var elem = doc.Descendants("Project").Where(t => t.Attribute("ToolsVersion")!=null)
                .Elements("ItemGroup").Elements("Reference").Where(r => r.Attribute("Include") != null);
            var attrs = elem.Attributes();
            Console.WriteLine(attrs.Count());
            foreach (var e in attrs)
            {
                Console.WriteLine(e);
            }

And this is my xml csproj file. I cut some unusfull text))

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

 <ApplicationIcon>icon.ico</ApplicationIcon>
 </PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xaml">
    <RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="MyProject1" />
<Reference Include="MyProject2" />
<Reference Include="MyProject3" />
 </ItemGroup>
 </Project>

Please, help me to get this list of names! What i do wrong?

Thank you.


回答1:


You're ignoring this:

xmlns="http://schemas.microsoft.com/developer/msbuild/2003"

That sets the default namespace for descendants. So you want:

XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
var elem = doc.Descendants(ns + "Project") 
              .Where(t => t.Attribute("ToolsVersion")!=null)
              .Elements(ns + "ItemGroup")
              .Elements(ns + "Reference")
              .Where(r => r.Attribute("Include") != null);


来源:https://stackoverflow.com/questions/19218163/parse-csproj-via-c-sharp-cannot-parse-itemgroup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!