为什么XDocument不读取元素值?

时间:2016-03-09 21:56:34

标签: c# linq proj

我的代码会读取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>

1 个答案:

答案 0 :(得分:1)

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

<AssemblyName>