C# 从csproj文件中读取引用列表
有人知道如何通过编程方式读取VS2008 csproj文件中的引用列表吗?MSBuild似乎不支持此功能。我试图通过将csproj文件加载到XmlDocument中来读取节点,但是XPath搜索不会返回任何节点。我正在使用以下代码:C# 从csproj文件中读取引用列表,c#,xpath,reference,.net-3.5,csproj,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.X
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);
}
如果我可以得到项目组列表,我可以确定它是否包含引用信息。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);
}
基于@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);
}
根据@PavelMinaev的回答,我还将HintPath元素添加到输出中。我将字符串数组引用写入.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);
那容易多了。谢谢你的帮助。这太棒了!到目前为止,每个人都可能注意到了这一点,但以防万一,也可以在解决方案中进行引用,在这种情况下,您还需要获取ProjectReference元素因为我用Resharper把它改成了var,之后我只遇到了问题!如果将其设为var,则从右侧将该类型推断为string。它必须是XNamespace,以便后者的字符串隐式转换运算符生效。