3

我尝试从 csproj 文件中获取所有 dll 名称,但什么也得不到!因此,我尝试使用 liq 查询从 ItemGroup 标记中获取所有元素:

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

这是我的 xml csproj 文件。我剪掉了一些不完整的文字))

<?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>

请帮我获取这份名单!我做错了什么?

谢谢你。

4

1 回答 1

16

你忽略了这个:

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

这为后代设置了默认命名空间。所以你要:

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);
于 2013-10-07T06:22:18.320 回答