简体   繁体   English

在C#中读取* .CSPROJ文件

[英]Reading a *.CSPROJ file in C#

I am attempting to write some code to read in a *.CSPROJ file using C# 我试图用C#编写一些代码来读取* .CSPROJ文件

The code I have is as follows 我的代码如下

   XmlDocument xmldoc = new XmlDocument();
   xmldoc.Load(fullPathName);

   XmlNamespaceManager mgr = new XmlNamespaceManager(xmldoc.NameTable);
   //mgr.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");

   foreach (XmlNode item in xmldoc.SelectNodes("//EmbeddedResource") )
   {
      string test = item.InnerText.ToString();
   }

using the debugger I can see that 'fullPathName" has the correct value and the xmldoc once loaded has the correct contents. 使用调试器我可以看到'fullPathName'具有正确的值,并且加载后的xmldoc具有正确的内容。

The xmldoc does not have any "Nodes" though, as if the contents are not recognised as XML. xmldoc没有任何“节点”,好像内容不被识别为XML。

Using a XML editor the *.csproj file validates an XML document. 使用XML编辑器,* .csproj文件验证XML文档。

Where am I going wrong? 我哪里错了?

Why not use the MSBuild API? 为什么不使用MSBuild API?

Project project = new Project();
project.Load(fullPathName);
var embeddedResources =
    from grp in project.ItemGroups.Cast<BuildItemGroup>()
    from item in grp.Cast<BuildItem>()
    where item.Name == "EmbeddedResource"
    select item;

foreach(BuildItem item in embeddedResources)
{
    Console.WriteLine(item.Include); // prints the name of the resource file
}

You need to reference the Microsoft.Build.Engine assembly 您需要引用Microsoft.Build.Engine程序集

You were getting close with your XmlNamespaceManager addition, but weren't using it in the SelectNodes method: 您正在接近添加XmlNamespaceManager,但未在SelectNodes方法中使用它:

XmlNamespaceManager mgr = new XmlNamespaceManager(xmldoc.NameTable);
mgr.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");

foreach (XmlNode item in xmldoc.SelectNodes("//x:ProjectGuid", mgr))
{
    string test = item.InnerText.ToString();
}

(I switched to searching for a different element as my project didn't have any embedded resources) (我切换到搜索不同的元素,因为我的项目没有任何嵌入资源)

For completeness here the XDocument version, this simplifies namespace management: 为了完整性,这里是XDocument版本,这简化了命名空间管理:

        XDocument xmldoc = XDocument.Load(fullPathName);
        XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";

        foreach (var resource in xmldoc.Descendants(msbuild + "EmbeddedResource"))
        {
            string includePath = resource.Attribute("Include").Value;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM