从csproj文件中读取参考列表

30

有人知道如何以编程方式读取VS2008 csproj文件中的引用列表吗?MSBuild似乎不支持这个功能。我尝试通过将csproj文件加载到XmlDocument中来读取节点,但XPath搜索没有返回任何节点。我正在使用以下代码:

System.Xml.XmlDocument projDefinition = new System.Xml.XmlDocument();
        projDefinition.Load(fullProjectPath);

        System.Xml.XPath.XPathNavigator navigator = projDefinition.CreateNavigator();

        System.Xml.XPath.XPathNodeIterator iterator = navigator.Select(@"/Project/ItemGroup");
        while (iterator.MoveNext())
        {
            Console.WriteLine(iterator.Current.Name);
        }

如果我能够获取ItemGroups列表,我就能够确定它是否包含参考信息。

3个回答

48
XPath应该是/Project/ItemGroup/Reference,并且您忘记了命名空间。我会使用XLINQ - 在XPathNavigator中处理命名空间相当混乱。所以:
    XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
    XDocument projDefinition = XDocument.Load(fullProjectPath);
    IEnumerable<string> references = projDefinition
        .Element(msbuild + "Project")
        .Elements(msbuild + "ItemGroup")
        .Elements(msbuild + "Reference")
        .Select(refElem => refElem.Value);
    foreach (string reference in references)
    {
        Console.WriteLine(reference);
    }

那真的容易多了。感谢你的帮助。 - user146059
太好了!现在大家可能都已经注意到了,但以防万一——引用也可以在解决方案内部进行,这种情况下,您还需要获取ProjectReference元素。 - astrowalker
非常重要的是不要更改这一行 XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003"; 因为我用 Resharper 把它改成了 var,然后我遇到了很多问题! - Patrick
如果你把它设为“var”,类型将从右侧被推断为“string”。必须是XNamespace,这样后者的从字符串的隐式转换操作符才会起作用。 - Pavel Minaev

11

在 @Pavel Minaev 的回答基础上,以下是对我有效的代码(请注意添加的 .Attributes 代码行以读取 Include 属性)

XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
    XDocument projDefinition = XDocument.Load(@"D:\SomeProject.csproj");
    IEnumerable<string> references = projDefinition
        .Element(msbuild + "Project")
        .Elements(msbuild + "ItemGroup")
        .Elements(msbuild + "Reference")
        .Attributes("Include")    // This is where the reference is mentioned       
        .Select(refElem => refElem.Value);
    foreach (string reference in references)
    {
        Console.WriteLine(reference);
    }

4

根据@PavelMinaev的答案,我还添加了“HintPath”元素到输出中。我将字符串数组“references”写入一个“.txt”文件。

XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
            XDocument projDefinition = XDocument.Load(@"C:\DynamicsFieldsSite.csproj");
            var references = projDefinition
                .Element(msbuild + "Project")
                .Elements(msbuild + "ItemGroup")
                .Elements(msbuild + "Reference")
                .Select(refElem => (refElem.Attribute("Include") == null ? "" : refElem.Attribute("Include").Value) + "\n" + (refElem.Element(msbuild + "HintPath") == null ? "" : refElem.Element(msbuild + "HintPath").Value) + "\n");
            File.WriteAllLines(@"C:\References.txt", references);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接