C#XML Linq,读取XML返回NullReferenceException

问题描述 投票:0回答:1

[首先,很抱歉-我搜索了一个例子,一个例子又一个例子,一个接一个地回答,在尝试了许多不同的例子之后,我仍然无法自己解决这个问题。

我有这样的XML处理:

<?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# xml linq xelement
1个回答
0
投票

感谢您对以上提供的帮助。其他遇到此问题的人的工作代码是:

      XElement xelement = XElement.Load("PathTo\\File.xml");
      IEnumerable<XElement> MyVehicleElements = xelement.Descendants("MyVehicleElements");
      foreach (var GetElements in MyVehicleElements)
      {
         Game.DisplayNotification((string)GetElements.Element("InVehicle"));
      }
© www.soinside.com 2019 - 2024. All rights reserved.