28

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

ItemGroup のリストを取得できれば、参照情報が含まれているかどうかを判断できます。

4

3 に答える 3

47

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);
    }
于 2009-07-27T23:24:01.277 に答える
11

@Pavel Minaevの答えに基づいて構築すると、これが私にとってうまくいきました(Include属性を読み取るために追加された.Attributes行に注意してください)

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);
    }
于 2015-02-24T11:09:05.833 に答える