如何修复'System.NullReferenceException:'Object reference not set to an instance of an object.'

How to fix 'System.NullReferenceException: 'Object reference not set to an instance of an object.'

我是 Xml 和 Linq 的新手,我一直在关注 youtube 上关于如何使用它的教程。

Link 到视频:https://www.youtube.com/watch?v=OsfVJ485RY4

问题是当我 运行 更改值或删除它的代码时,我总是得到以下错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Xml.Linq.XElement.Attribute(...) returned null.

首先我加载我的文档:

XDocument xmlDocument = XDocument.Load(@"C:\Users\matpl\source\repos\LinqToXML\LinqToXML\Data.xml");

我要更改 Xml 文档值的部分

xmlDocument.Element("Students")
           .Elements("Student")
           .Where(x => x.Attribute("Id").Value == "101").FirstOrDefault()
           .SetElementValue("TotalMarks", "999");

当我要删除一个元素时:

xmlDocument.Root.Elements().Where(x => x.Attribute("Id").Value == "104").Remove();

XML 文件:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Comment Updated-->
<Students>
  <Student>
    <Student Id='101'>
      <Name>Mark</Name>
      <Gender>Male</Gender>
      <TotalMarks>800</TotalMarks>
    </Student>
    <Student Id='102'>
      <Name>Rosy</Name>
      <Gender>Female</Gender>
      <TotalMarks>900</TotalMarks>
    </Student>
    <Student Id='103'>
      <Name>Pam</Name>
      <Gender>Female</Gender>
      <TotalMarks>850</TotalMarks>
    </Student>
    <Student Id='104'>
      <Name>John</Name>
      <Gender>Male</Gender>
      <TotalMarks>950</TotalMarks>
    </Student>
  </Student>
  <Student Id='105'>
    <Name>Todd</Name>
    <Gender>Male</Gender>
    <TotalMarks>980</TotalMarks>
  </Student>
</Students>

谢谢,

StudentsStudent-101之间还有一个Student元素。看来你错了 xml:

<Students>
  <Student> //WHAT IS IT?
    <Student Id='101'>
      <Name>Mark</Name>
      <Gender>Male</Gender>
      <TotalMarks>800</TotalMarks>
    </Student>
    <Student Id='102'>
      <Name>Rosy</Name>
      <Gender>Female</Gender>
      <TotalMarks>900</TotalMarks>
    </Student>
    <Student Id='103'>
      <Name>Pam</Name>
      <Gender>Female</Gender>
      <TotalMarks>850</TotalMarks>
    </Student>
    <Student Id='104'>
      <Name>John</Name>
      <Gender>Male</Gender>
      <TotalMarks>950</TotalMarks>
    </Student>
  </Student> //WHAT IS IT?
  <Student Id='105'>
    <Name>Todd</Name>
    <Gender>Male</Gender>
    <TotalMarks>980</TotalMarks>
  </Student>
</Students>

检查此 https://dotnetfiddle.net/14js9r。它可以在正确的 xml.

下正常工作