从csproj文件中读取引用列表

时间:2009-07-27 23:16:00

标签: c# xpath reference .net-3.5 csproj

有没有人知道以编程方式读取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 个答案:

答案 0 :(得分:38)

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

答案 1 :(得分:8)

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

答案 2 :(得分:4)

根据@ PavelMinaev的回答,我还添加了&#34; HintPath&#34;元素到输出。我写了字符串数组&#34;引用&#34;到&#34; .txt&#34;文件。

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