0

我有读取proj文件并检查其assembly名称的代码。

XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument projDefinition = XDocument.Load(projPath);
          assemblyName = projDefinition
          .Element(msbuild + "Project")
          .Element(msbuild + "PropertyGroup")
          .Element(msbuild + "AssemblyName")
          .Value;

上面的代码在 99% 的时间里都能完美运行。今天它Null Object Reference Exception试图assembly从下面的代码中获取名称。顶部property group elementimport element通常朝向proj文件的底部。

我的问题是为什么XDocument不过去Import Element也不接其他propertygroup elements

<PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <UseGlobalApplicationHostFile />
  </PropertyGroup>
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>


Some Elements ...

<AssemblyName>AssemblyNameGoesHere</AssemblyName>
4

1 回答 1

1

根据您提供的 XML 片段,我认为问题的根源在于您的 XML 查询正在查找<PropertyGroup>不包含子<AssemblyName>元素的元素,因此您的NULL reference exception. 您可能需要的是收集所有<PropertyGroup>元素的代码,遍历它们以查找<AssemblyName>元素并返回您为它找到的第一个值。

XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument projDefinition = XDocument.Load(@"C:\Path\To\Project.csproj");

var propertyGroups = projDefinition.Element(msbuild + "Project")
    .Elements(msbuild + "PropertyGroup");

string assemblyNameValue = "";

foreach (XElement propertyGroup in propertyGroups)
{
    //Check if this <PropertyGroup> elements contains a <AssemblyName> element
    if (propertyGroup.Element(msbuild + "AssemblyName") != null)
    {
        assemblyNameValue = propertyGroup.Element(msbuild + "AssemblyName").Value;
        break;
    }
}

Console.WriteLine("AssemblyName: " + assemblyNameValue);
于 2016-03-09T23:18:51.463 回答