【问题标题】:C# XML Linq, reading XML returns NullReferenceExceptionC# XML Linq,读取 XML 返回 NullReferenceException
【发布时间】:2020-05-16 21:05:57
【问题描述】:

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

我有一个像这样的 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"
     }

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

【问题讨论】:

  • 我无法重现任何问题,请参阅dotnetfiddle.net/XlDVXI。为MyVehicleElements.Element("InVehicle").Value 打印的值是true。我们需要查看minimal reproducible example(一个可编译的、独立的示例控制台应用程序,它显示了问题,但没有引用Game 等外部对象)来帮助您。如需一般帮助,请参阅What is a NullReferenceException, and how do I fix it?
  • 代码中的哪一行抛出了“NullReferenceException”?是xelement.Elements() 还是MyVehicleElements.Element("InVehicle")
  • 您可能遇到了编码问题。当您发布 xml 时,它可能会更改字符的编码。尝试使用发布的 xml,看看是否仍有错误。
  • 你写的代码很好,所以请分享整个xml,它可能有编码问题。
  • 您必须解决问题 1) 不要将 Value 与 Xml Linq 一起使用。当对象不存在时,您将收到异常。而是像这样转换: var InVehicle = (string)GetElements.Element("InVehicle"); 2) InVehicle 不是孩子,它是后代,所以使用这个:IEnumerable MyVehicleElements = xelement.Descendants("MyVehicleElements");

标签: c# xml linq xelement


【解决方案1】:

感谢以上所有帮助的人。遇到此问题的其他人的工作代码是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    相关资源
    最近更新 更多