【问题标题】:Why XDocument isn't reading elements value?为什么 XDocument 不读取元素值?
【发布时间】:2016-06-24 12:40:28
【问题描述】:

我的代码可以读取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% 的情况下都能完美运行。今天,当它试图从下面的代码中获取 assembly 名称时,它得到了 Null Object Reference Exception。顶部的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>

【问题讨论】:

    标签: c# linq proj


    【解决方案1】:

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

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

    【讨论】:

    • 完美运行。 assemblyname 并不总是在第一个属性组中,但我认为 Import 元素正在将其设置为关闭。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    相关资源
    最近更新 更多