首页 > 解决方案 > C# XML Linq,读取 XML 返回 NullReferenceException

问题描述

首先,我很抱歉 - 我已经搜索和搜索,尝试了一个又一个例子,一个又一个答案,在尝试了很多不同的例子之后,我仍然无法让它为自己工作。

我有一个像这样的 XML smoeth:

<?xml version="1.0" encoding="utf-8"?>
<Backup LastRun="Saturday, May 16, 2020 7:58:53 PM">
    <MyVehicleElements>
        <InVehicle>true</InVehicle>
        ... etc ...
    </MyVehicleElements>
</Backup>

而且我的代码无法返回空异常,因为我一生都无法弄清楚如何阅读额外的级别。

XElement xelement = XElement.Load("PathTo\\File.xml");
IEnumerable<XElement> Backup = xelement.Elements();
     foreach (var MyVehicleElements in Backup)
     {
         Game.DisplayNotification(MyVehicleElements.Element("InVehicle").Value); 
         // Should return text "true"
     }

在我的头爆炸之前,请有人帮助我。先感谢您。

标签: c#xmllinqxelement

解决方案


谢谢楼上所有帮助过的人。遇到此问题的其他任何人的工作代码是:

      XElement xelement = XElement.Load("PathTo\\File.xml");
      IEnumerable<XElement> MyVehicleElements = xelement.Descendants("MyVehicleElements");
      foreach (var GetElements in MyVehicleElements)
      {
         Game.DisplayNotification((string)GetElements.Element("InVehicle"));
      }

推荐阅读